1

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");

?

Doc
  • 5,078
  • 6
  • 52
  • 88

3 Answers3

8

this should do it:

bool attr1_exist = MyList.Exists(s=> s.attr1 == "aaa")
Michael B
  • 581
  • 1
  • 5
  • 17
  • thanks! but what's the difference between using .Any or .Exists? – Doc Feb 06 '14 at 10:22
  • Both are effectively the same method, .Any() is available from .net 3.5 and upwards. I work with .net 2.0 so suggested Exists() from habit I guess. Maybe @DGibbs could suggest why he used .Any? – Michael B Feb 06 '14 at 10:27
  • @MichaelB Pretty much the same reason, I use newer versions of the framework though. `Any()` is slightly different in that it can be used without a lambda e.g. `MyList.Any()` will return true if the list has any items, other than that, they are essentially the same. – DGibbs Feb 06 '14 at 10:53
0

Use Any():

bool attr1_exist = MyList.Any(x => x.attr1.Contains("aaa"));
DGibbs
  • 14,316
  • 7
  • 44
  • 83
0

Try Following Code:

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

OR

if(MyList.Where(n=> n.attr1 == "aaa").Count() > 0)
{
    //Do Somthing . . .
}
AliNajafZadeh
  • 1,216
  • 2
  • 13
  • 22