Doc
Doc

Reputation: 5266

Check if object in list has specific field content

Sorry for question title, I don't know really how to explain it in a single sentence...

I have a class like this

public class xyz
{
    public static string attr1;
    public static string attr2;
    public static string attr3;
}

how can i check if there is an object with attr1=="aaa" in a List<xyz>?

is there something like

List<xyz> MyList = new List<xyz>();

[...]

bool attr1_exist = MyList.attr1.Contains("aaa");

?

Upvotes: 1

Views: 8416

Answers (3)

AliNajafZadeh
AliNajafZadeh

Reputation: 1328

Try Following Code:

Boolean IsExist = MyList.Any(n=> n.attr1 == "aaa");

OR

if(MyList.Where(n=> n.attr1 == "aaa").Count() > 0)
{
    //Do Somthing . . .
}

Upvotes: 0

DGibbs
DGibbs

Reputation: 14618

Use Any():

bool attr1_exist = MyList.Any(x => x.attr1.Contains("aaa"));

Upvotes: 0

Michael B
Michael B

Reputation: 581

this should do it:

bool attr1_exist = MyList.Exists(s=> s.attr1 == "aaa")

Upvotes: 8

Related Questions