Using .Contains() on a property in a list

前端 未结 8 577
庸人自扰
庸人自扰 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
    }
    
    0 讨论(0)
  • 2020-12-10 18:33
    foreach(var activity in ActivityList.Where(p=>p.Id == GuidToCompare))
    {
    
    // Code here
    
    }
    
    0 讨论(0)
提交回复
热议问题