Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

Possible Duplicate:
Check if all items are the same in a List

I have a list:

{string, string, string, string}

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?

like image 875
hs2d Avatar asked Nov 28 '22 03:11

hs2d


2 Answers

var allAreSame = list.All(x => x == list.First());
like image 131
Daniel Hilgarth Avatar answered Dec 05 '22 15:12

Daniel Hilgarth


var allAreSame = list.Distinct().Count() == 1;

or a little more optimal

var allAreSame = list.Count == 0 || list.All(x => x == list[0]);
like image 25
Petar Ivanov Avatar answered Dec 05 '22 16:12

Petar Ivanov