Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all List Items have the same member value in C#

Tags:

c#

I'm searching for a simple and fast way to check if all my Listitems have the same value for a member.

foreach (Item item in MyList)
{
    Item.MyMember = <like all other>;
}

EDIT: I forgot one thing: If one of this members (its a string) is String.Empty and all other items have the same string it should be true too! Sorry i forgot this.

like image 238
Sebastian Avatar asked Aug 05 '11 12:08

Sebastian


3 Answers

EDIT: Okay, after the new requirement has

bool allSame = !MyList.Select(item => item.MyMember)
                      .Where(x => !string.IsNullOrEmpty(x))
                      .Distinct()
                      .Skip(1)
                      .Any();

That avoids you having to take a first step of finding one sample value to start with. (And it will still exit as soon as it finds the second value, of course.)

It also only iterates over the sequence once, which may be important if it's not really a repeatable sequence. Not a problem if it's a List<T> of course.

EDIT: To allay concerns over Skip, from the documentation:

If source contains fewer than count elements, an empty IEnumerable<T> is returned. If count is less than or equal to zero, all elements of source are yielded.

like image 159
Jon Skeet Avatar answered Sep 28 '22 13:09

Jon Skeet


Your own solution is simple enough already, but if you wanted to abstract away the loop and write it more expressively, you could use Linq.

bool allSame = MyList.All(item => item.MyMember == someValue);
like image 27
Anthony Pegram Avatar answered Sep 28 '22 12:09

Anthony Pegram


using System.Linq;
…

if (myList.Any()) // we need to distinguish between empty and non-empty lists 
{
    var value = myList.First().MyMember;
    return myList.All(item => item.MyMember == value);
}
else
{
    return true;  // or false, if that is more appropriate for an empty list    
}
like image 23
stakx - no longer contributing Avatar answered Sep 28 '22 13:09

stakx - no longer contributing