在唯一列表c#

时间:2018-03-21 10:07:48

标签: c# list

我有一个嵌套的List,例如:

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

谢谢

1 个答案:

答案 0 :(得分: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;
}

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