将嵌套列表的元素合并为唯一列表 c#

4

I have a nested List as in the example:

List<List<int>> myList = new List<List<int>>();
myList.Add(new List<int> { 2, 7, 3 });
myList.Add(new List<int> { 4, 6});
myList.Add(new List<int> { 2, 5, 1 });
myList.Add(new List<int> { 7, 0, 2 });
myList.Add(new List<int> { 4, 9 });

我希望将所有至少有一个共同元素的列表合并,使输出成为一个List<List<int>>,其中包含以下元素:

List<int> 2, 7, 3, 5, 1, 0
List<int> 4,6,9

谢谢你


你可以使用 Linq 的 Intersect 方法来检查两个列表是否包含共同的元素。 - o_weisman
2
棘手的问题,比看起来更难,我个人认为。 - Pac0
1个回答

7
你可以使用 HashSet 来解决问题,尽管我相信效率可以得到提高:
public static void Main(string[] args)
{
    List<List<int>> myList = new List<List<int>>();
    myList.Add(new List<int> { 2, 7, 3 });
    myList.Add(new List<int> { 4, 6});
    myList.Add(new List<int> { 2, 5, 1 });
    myList.Add(new List<int> { 7, 0, 2 });
    myList.Add(new List<int> { 4, 9 });
    var result = FindCommonSets(myList);
}

static List<HashSet<T>> FindCommonSets<T>(IEnumerable<IEnumerable<T>> data)
{
    List<HashSet<T>> sets = new List<HashSet<T>>();
    bool anyModified = false;
    foreach (var list in data)
    {
        //find a set which already overlaps this list.
        var set = sets.FirstOrDefault(s => s.Overlaps(list));
        if (set != null)
        {
            //if we find one, dump all the elements of this list into the set.
            set.UnionWith(list);
            anyModified = true;
        }
        else
        {
            //if not, add a new set based on this list.
            sets.Add(new HashSet<T>(list));
        }
    }
    if (anyModified)
    {
        //run the whole thing again with the new data if anything was changed in this iteration.
        return FindCommonSets(sets);
    }
    return sets;
}

编辑:根据评论中提出的问题,改为递归实现。


2
棘手的问题。您的解决方案适用于OP中的输入示例,但对于例如:{ 2, 7, 3 }, { 4, 6 }, { 5, 1 }, { 7, 0, 2 }, { 4, 9 }, { 2, 5 }则不起作用。在这种情况下,最后一个{2, 5}应该导致两个已经存在的集合合并为一个,但您的代码并没有实现这一点。 - Pac0
3
我认为解决方法是使用新的集合重复合并,直到不再需要合并集合为止。 - Peter B

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接