开发者

c# Check if all strings in list are the same [duplicate]

This question already has answers here: Closed 11 years ago.

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜