Using .Contains() on a property in a list

前端 未结 8 576
庸人自扰
庸人自扰 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:12

    I Havent tested it but im fairly sure this should work:

    if ( ActivityList.Any ( a => a.Id == GuidToCompare ) ) {
        // TODO - Exists.
    }
    

    MSDN Any : http://msdn.microsoft.com/en-us/library/bb534972.aspx

    0 讨论(0)
  • 2020-12-10 18:13

    Just to offer you all the ways you can write this query with Linq

    var result = (from activity in activityList
                  where activity.Id == GuidToCompare
                  select activity ).FirstOrDefault();
    
    if(result != null)
        /* Code here */
    

    Now, it is up to you to choose the more readable snippet ;)

    0 讨论(0)
  • 2020-12-10 18:16

    If you are looking for only one Id one time, there is no more efficient way.

    If you are looking for Ids multiple times you can build a HashSet :

    var activityIdsQuery = from a in ActivityList
                           select a.Id;
    HashSet<Guid> activityIds = new HashSet<Guid>(activityIdsQuery);
    
    //Use the hashset
    activityIds.Contains(id);
    

    If you need to find an instance of activity you can build a Dictionary (works only if Id is unique) :

    Dictionary<Guid, Activity> activities = ActivityList.ToDictionary(a => a.Id);
    

    Others solution using Linq with Where/FirstOrDefault/Any on the Id won't be more efficient than yours.

    0 讨论(0)
  • 2020-12-10 18:20

    For those who can't use LINQ:

    List<Activity> ActivityList = new List<Activity>();
    
    foreach (Activity activity in ActivityList.FindAll(delegate(Activity a)
        {
            return a.Id == GuidToCompare;
        }))
    {
        //Code here
    }
    
    0 讨论(0)
  • 2020-12-10 18:25

    Take a look to the LINQ, You can replace with it your code by: ActivityList.Any(i => i.Id == GuidToCompare);

    0 讨论(0)
  • 2020-12-10 18:26

    to find all activity objects with the given GUID you can use:

    var results = ActivityList.FindAll(item => item.ID == GuidToCompare);
    
    0 讨论(0)
提交回复
热议问题