从结构列表中选择项目

时间:2012-01-11 16:52:38

标签: c# linq list

我有结构清单。在struct中有字段x。我想选择结构的那些,它们通过参数x相互接近。换句话说,我想用x对它们进行聚类。 我猜,应该有单线解决方案。 提前谢谢。

3 个答案:

答案 0 :(得分:4)

如果我理解了你想要的东西,那么你可能需要按结构的字段X对列表进行排序。

答案 1 :(得分:2)

查看GroupBy扩展方法:

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

This article使用group by提供了大量示例。

答案 2 :(得分:0)

如果您正在进行图形式群集,最简单的方法是建立一个最初为空的群集列表。然后遍历输入,并且对于每个值,找到具有至少一个接近当前值的元素的所有簇。然后应将所有这些集群与值合并在一起。如果没有,则该值将自动进入集群。

以下是一些示例代码,介绍如何使用简单的整数列表。

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());
}
相关问题