为了账号安全,请及时绑定邮箱和手机立即绑定

简化迭代到 linq 查询

简化迭代到 linq 查询

C#
大话西游666 2023-09-16 17:03:22
我目前正在开发 .NET 4.7.1 应用程序。给定一个 for 循环来比较 2 个列表并检查是否有任何 Id 已更改。如果列表 1 中的任何 Id 与列表 2 中的任何 Id 不同,我需要返回 null,否则返回列表 2。我目前通过简单的迭代解决了这个问题。尽管如此,我想知道是否可以使用 LINQ 语句更轻松地解决这个问题。var list1 = new List<string>{  "A",  "B",  "C"};var list2 = new List<string>{  "A",  "C",  "B"};private List<string> Compare(){ if (list1 != null) {    for (int i = 0; i < list1.Count; i++)    {        if (list1[i] != list2[i])        {            return list2;        }    }    return null; } return list2;}您知道如何解决这个问题而不是使用 for 循环,而是使用 LINQ 语句吗?谢谢!
查看完整描述

2 回答

?
杨魅力

TA贡献1811条经验 获得超5个赞

这是 For 循环的一种 linq 替代方案


   private List<string> Compare()

    {

        if (list1 == null) return list2;

        if (list1.Where((x, i) => x != list2[i]).Any())

        {

            return list2;

        }


        return null;

    }



查看完整回答
反对 回复 2023-09-16
?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

您可以使用Zip将项目分组在一起来比较它们,然后All确保它们相同:


private List<string> Compare()

{


 if (list1 == null) return list2;

 if (list1.Count != list2.Count) return null;


 bool allSame = list1.Zip(list2, (first, second) => (first, second))

                     .All(pair => pair.first == pair.second);



 return allSame ? list2 : null;

}

注意:该Zip函数用于将两个项目放入一个元组中(第一个,第二个)。


您还可以使用SequenceEqual


private List<string> Compare()

{


 if (list1 == null) return list2;


 bool allSame = list1.SequenceEqual(list2);      

 return allSame ? list2 : null;

}


查看完整回答
反对 回复 2023-09-16
  • 2 回答
  • 0 关注
  • 58 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信