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

后端 未结 6 1520
遇见更好的自我
遇见更好的自我 2020-12-19 10:32

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 = &         


        
6条回答
  •  星月不相逢
    2020-12-19 11:11

    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 of course.

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

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

提交回复
热议问题