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
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
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 ;)
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.
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
}
Take a look to the LINQ, You can replace with it your code by: ActivityList.Any(i => i.Id == GuidToCompare);
to find all activity objects with the given GUID you can use:
var results = ActivityList.FindAll(item => item.ID == GuidToCompare);