Using .Contains() on a property in a list

前端 未结 8 575
庸人自扰
庸人自扰 2020-12-10 18:01

I have a List of Activity. In the Activity class is an ID property (a Guid for arguments sake). I want to check if this list has an Activity in it with a Guid I have. Rather

8条回答
  •  攒了一身酷
    2020-12-10 18:31

    Sure.

    foreach(Activity activity in ActivityList.Where(a => a.Id == GuidToCompare) )
    {        
        //Code here
    }
    

    But since Id implies there will be at most 1 activity:

    //var act = ActivityList.Where(a => a.Id == GuidToCompare).SingleOrDefault(); // clearer
    var act = ActivityList.SingleOrDefault(a => a.Id == GuidToCompare);          // shorter
    if (act != null)
    {
        //Code here
    }
    

提交回复
热议问题