简体   繁体   中英

Select items from List of structs

I've got List of sctructs. In struct there is field x. I would like to select those of structs, which are rather close to each other by parameter x. In other words, I'd like to clusterise them by x. I guess, there should be one-line solution. Thanks in advance.

如果我正确理解了您想要的内容,则可能需要按结构的字段X对列表进行排序。

Look at the GroupBy extension method:

var items = mylist.GroupBy(c => c.X);

This article gives a lot of examples using group by .

If you're doing graph-style clustering, the easiest way to do it is by building up a list of clusters which is initially empty. Then loop over the input and, for each value, find all of the clusters which have at least one element which is close to the current value. All those clusters should then be merged together with the value. If there aren't any, then the value goes into a cluster all by itself.

Here is some sample code for how to do it with a simple list of integers.

IEnumerable<int> input;
int threshold;

List<List<int>> clusters = new List<List<int>>();

foreach(var current in input)
{
    // Search the current list of clusters for ones which contain at least one
    // entry such that the difference between it and x is less than the threshold
    var matchingClusters = 
        clusters.Where(
            cluster => cluster.Any(
                           val => Math.Abs(current - val) <= threshold)
        ).ToList();

    // Merge all the clusters that were found, plus x, into a new cluster.
    // Replace all the existing clusters with this new one.
    IEnumerable<int> newCluster = new List<int>(new[] { current });
    foreach (var match in matchingClusters)
    {
        clusters.Remove(match);
        newCluster = newCluster.Concat(match);
    }
    clusters.Add(newCluster.ToList());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM