【问题标题】:Linq, determine if list are equalsLinq,确定列表是否相等
【发布时间】:2016-03-13 07:36:42
【问题描述】:

如何确定List<List<int>> 中的项目是否相等?

List<List<int>> equals = new List<List<int>>()
{
    new List<int>() { 1,2 },
    new List<int>() { 1,2 }
};

List<List<int>> notEquals = new List<List<int>>()
{
    new List<int>() { 1,2 },
    new List<int>() { 2,500}
};

【问题讨论】:

  • 列表{1, 2}{2, 1} 是否相等?顺序重要吗?
  • 你有什么尝试吗?
  • @DmitryBychenko 顺序无关紧要。
  • @SergiiZhevzhyk 。没有重复。在我的示例中,我只有 2 个项目,但最终更多
  • @BobyOneKenobi:在这种情况下,接受的 Tim Schmelter 的答案是不是您正在寻找的答案:SequenceEqual取决于订单。

标签: c# linq


【解决方案1】:

您需要将第一个列表与所有其他列表进行比较,您可以使用SequenceEqual

List<int> first = yourLists[0];
bool allEqual = yourLists.Skip(1).All(l => first.SequenceEqual(l));

由于All 在第一个不相等的列表中返回false,这非常有效。

【讨论】:

  • 好。但这不起作用吗? bool allEqual = first.SequenceEqual(yourLists[1]);
  • @user2946329:如果列表只能包含两个也可以使用的子列表。但即使我的方法包含两个以上,我的方法也有效。您仅将第一个列表与第二个列表进行比较。如果有第三个列表不相等怎么办?
  • 对。所以你的回答更全面。
猜你喜欢
  • 2016-12-07
  • 2011-06-29
  • 2021-09-04
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-13
相关资源
最近更新 更多