2 回答

TA貢獻1811條經驗 獲得超6個贊
這是 For 循環的一種 linq 替代方案
private List<string> Compare()
{
if (list1 == null) return list2;
if (list1.Where((x, i) => x != list2[i]).Any())
{
return list2;
}
return null;
}

TA貢獻1906條經驗 獲得超3個贊
您可以使用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;
}
- 2 回答
- 0 關注
- 136 瀏覽
添加回答
舉報