c#检查列表中的所有字符串是否相同
本文关键字:字符串 是否 检查 列表 | 更新日期: 2023-09-27 18:01:53
可能重复:
检查列表中的所有项目是否相同
我有一个清单:
{string, string, string, string}
我需要检查这个列表中的所有项目是否相同,然后返回true,如果不返回false。
我可以用LINQ做这个吗?
var allAreSame = list.All(x => x == list.First());
var allAreSame = list.Distinct().Count() == 1;
或者更优化的
var allAreSame = list.Count == 0 || list.All(x => x == list[0]);
这个怎么样:
string[] s = { "same", "same", "same" };
if (s.Where(x => x == s[0]).Count() == s.Length)
{
return true;
}
var hasIdenticalItems = list.Count() <= 1 || list.Distinct().Count() == 1;