gpt4 book ai didi

c# - 如何将多个对象传递到 IEnumerable 列表中?

转载 作者:太空狗 更新时间:2023-10-30 00:30:34 25 4
gpt4 key购买 nike

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

我不知道如何将多个列表传递到一个 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

如何正确调用它?我必须以某种方式将它们合并到 IEnumerable 中吗?还是我必须以某种方式将它们全部组合到 1 个列表中,同时保留某种隐形分隔线?

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

P.S.> 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);
}

最佳答案

您可以使用 params 关键字很好地完成此操作。在你的例子中:

static List<T> FindCommon<T>(params List<T>[] lists)

这将实现用法:

List<uint> Commons = FindCommon(List1, List2, List3);

关于c# - 如何将多个对象传递到 IEnumerable 列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34943965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com