gpt4 book ai didi

C# Linq 检查列表列表是否在列表列表中

转载 作者:行者123 更新时间:2023-11-30 19:52:42 25 4
gpt4 key购买 nike

我有两个列表列表:
(1) 变体 和 (2) 选项

我需要查看变体中是否存在所有选项(无论顺序如何)。

例如:在下面的代码中,我需要确保每个项目列表都出现在变体列表中 - 因此无论顺序如何,列表“蓝色”、“红色”、“绿色”都必须出现在变体列表中

编辑(澄清):“选项”中的所有列表都必须出现在“变体”中。如果其中之一失败,则 bool 值必须返回 false。

我设置了一个 LINQ 条件,但不确定它为什么不起作用。任何帮助将不胜感激。

 //TEST 1

List<List<string>> variants = new List<List<string>>();
variants.Add(new List<string> {"cars", "boats", "planes"});
variants.Add(new List<string> {"money", "trees", "plants"});
variants.Add(new List<string> {"green", "blue", "red" });
variants.Add(new List<string> {"kid", "adult", "senior"});
variants.Add(new List<string> {"tax", "insurance", "salary"});

List<List<string>> options = new List<List<string>>();
options.Add(new List<string> { "senior", "adult", "kid" });
options.Add(new List<string> { "blue", "red", "green"});
options.Add(new List<string> {"money", "trees", "plants"});

bool exists = variants.Any(a => options.Any(b => b.SequenceEqual(a.OrderBy(x => x))));

Console.WriteLine(exists);
// The result should be TRUE even though the order of "senior", "adult" and "kid"
// is different and that the order of listed items is different


//TEST 2
List<List<string>> options2 = new List<List<string>>();
options2.Add(new List<string> { "senior", "adult", "kid" });
options2.Add(new List<string> { "orange", "red", "green"});
options2.Add(new List<string> {"money", "trees", "plants"});

exists = variants.Any(a => options2.Any(b => b.SequenceEqual(a.OrderBy(x => x))));

Console.WriteLine(exists);
// The result should be FALSE. All listed options are TRUE except that the 2nd list has
// "orange" which doesn't appear in the variants list.



//TEST 3
List<List<string>> options3 = new List<List<string>>();
options3.Add(new List<string> { "senior", "red", "adult" });
options3.Add(new List<string> { "blue", "kid", "green"});
options3.Add(new List<string> {"money", "trees", "plants"});

exists = variants.Any(a => options3.Any(b => b.SequenceEqual(a.OrderBy(x => x))));

Console.WriteLine(exists);
// The result should be FALSE. All of the items actually exist in the variant list,
// but "senior", "kid", and "adult" do not appear together within a list of variants.

最佳答案

您可以为每个变体列表构建一个HashSet,然后检查每个选项列表是否至少有一个变体集包含所有选项:

List<HashSet<string>> variantSets = variants.Select(vl => new HashSet<string>(vl)).ToList();

bool allIncluded = options.All(ol => variantSets.Any(vs => ol.All(vs.Contains)));

Link to Fiddle

关于C# Linq 检查列表列表是否在列表列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54950914/

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