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.
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.
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);
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With