c# Check if all strings in list are the same [duplicate]
Possible Duplicate:
Check if all items are the same in a List
I have a list:
{string, string, string, s开发者_C百科tring}
I need to check if all the items in this list are the same then return true, if not return false.
Can i do this with LINQ?
var allAreSame = list.All(x => x == list.First());
var allAreSame = list.Distinct().Count() == 1;
or a little more optimal
var allAreSame = list.Count == 0 || list.All(x => x == list[0]);
How about this:
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;
精彩评论