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

标签 c# list linq

我有两个列表列表:
(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/

相关文章:

java - 检查列表是否包含相同的对象

c# - 增加字典中存在的键的值

c# - HttpClient.SendRequestAsync 触发 StackOverflow

python - map(sum,zip(*list)) 是对任意长度列表的列求和的最快方法吗?

c# - 通过 Linq 表达式指定 MethodInfo 的面向 future 的方法

c# - 帮助 Linq 查询

Linq-EF : How to query a Junction table?

c# - 使用 ? 时出现 CA2213 警告。 (空条件运算符)调用 Dispose

c# - 使用必填字段验证器时如何清除控件?

python - 如何操作列表