如何将多个对象传递到IEnumerable列表?

SSp*_*oke 4 .net c# vb.net list

我有这段代码,似乎支持将许多列表参数传递给它,它会将每个参数相互比较,以便同时在所有其他列表中找到一个公共列表.

我无法弄清楚如何将多个列表传递给一个IEnmerable的参数.

说我的测试代码看起来像这样

List<uint> List1 = new List<uint>();
List<uint> List2 = new List<uint>();
List<uint> List3 = new List<uint>();

List<uint> Commons = FindCommon(List1, List2, List3); //no compile
List<uint> Commons = FindCommon<List<uint>>(List1, List2, List3); //no compile?? why
Run Code Online (Sandbox Code Playgroud)

我怎么称呼这个?我必须以某种方式将它们合并到IEnumerable中吗?或者我必须以某种方式将它们全部合并到一个列表中,同时保留某种不可见的分隔符?

 static List<T> FindCommon<T>(IEnumerable<List<T>> lists)
    {
        Dictionary<T, int> map = new Dictionary<T, int>();
        int listCount = 0; // number of lists

        foreach (IEnumerable<T> list in lists)
        {
            listCount++;
            foreach (T item in list)
            {
                // Item encountered, increment count
                int currCount;
                if (!map.TryGetValue(item, out currCount))
                    currCount = 0;

                currCount++;
                map[item] = currCount;
            }
        }

        List<T> result= new List<T>();
        foreach (KeyValuePair<T,int> kvp in map)
        {
            // Items whose occurrence count is equal to the number of lists are common to all the lists
            if (kvp.Value == listCount)
                result.Add(kvp.Key);
        }

        return result;
    }
Run Code Online (Sandbox Code Playgroud)

PS> FindCommon以某种方式被破坏它不能正常工作,可能不是我认为它应该做的...它不会同时检查所有列表一起只有线性一个列表一次与另一个列表打破它的目的,它将它们计算在内......但它并没有跟踪它们来自哪个列表.

像这样固定它,这种方法按预期工作.

public static List<T> FindCommon<T>(params List<T>[] lists)
{
    SortedDictionary<T, bool>
      current_common = new SortedDictionary<T, bool>(),
      common = new SortedDictionary<T, bool>();

    foreach (List<T> list in lists)
    {
        if (current_common.Count == 0)
        {
            foreach (T item in list)
            {
                common[item] = true;
            }
        }
        else
        {
            foreach (T item in list)
            {
                if (current_common.ContainsKey(item))
                {
                    common[item] = true;
                }
            }
        }

        if (common.Count == 0)
        {
            current_common.Clear();
            break;
        }

        SortedDictionary<T, bool>
          swap = current_common;

        current_common = common;
        common = swap;
        common.Clear();
    }

    return new List<T>(current_common.Keys);
}
Run Code Online (Sandbox Code Playgroud)

Sim*_*son 7

您可以使用params关键字很好地完成此任务.在你的例子中:

static List<T> FindCommon<T>(params List<T>[] lists)
Run Code Online (Sandbox Code Playgroud)

这将实现用法:

List<uint> Commons = FindCommon(List1, List2, List3);
Run Code Online (Sandbox Code Playgroud)