从结构列表中选择项目

本文关键字:选择 项目 列表 结构 | 更新日期: 2023-09-27 18:19:57

我有scstructs列表。struct中有字段x。我想选择那些通过参数x彼此非常接近的structs。换句话说,我想通过x对它们进行聚类。我想,应该有一条线的解决方案。提前谢谢。

从结构列表中选择项目

如果我正确理解您想要什么,那么您可能需要根据结构的字段X对列表进行排序。

查看GroupBy扩展方法:

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

本文给出了大量使用CCD_ 2的例子。

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

以下是一些示例代码,说明如何使用一个简单的整数列表来完成此操作。

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());
}