Chaddeus
Chaddeus

Reputation: 13356

In C#, how to check if a property of an object in a List<> contains a string?

Let's say I have an object like:

class Thing {
  string Id;
  string Name;
  string Message;
}

and a List<Thing>. Before I add a new Thing to the list, I want to check to make sure the list doesn't already contain the thing, but I don't have a purely identical thing to compare with (so can't do list.Contains(Thing), but I want to do something like that)

The Thing.Message property could be the same, but other properties different.

How can I check the List<Thing> to see if it contains a Thing which has a .Message property equal to a specific string?

Upvotes: 1

Views: 417

Answers (2)

millimoose
millimoose

Reputation: 39950

var addedThing = new Thing {…};
if (!things.Any(t=>t.Message == addedThing.Message)) {
    things.Add(addedThing);
}

Upvotes: 2

Kieren Johnstone
Kieren Johnstone

Reputation: 41983

Linq!

if (myList.Any(t => t.Message == "hello"))

Upvotes: 5

Related Questions