Using .Contains () for a property in a list

I have a list of actions. The Activity class has an ID property (Guid for arguments). I want to check if there is an Activity in this list in it with the Guid that I have. Instead of this:

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

Is there a more efficient way to achieve the same result as I would if I only had a list of Guides (instead of an Activity list) and use .Contains ()?

I have a list of structures called ActivityAndPO. Guid is in this structure. I have a PO list. There is a Guid in the PO class.

I want to iterate over all the objects in the ActivityAndPO list, where Guid is in the PO list.

+6
source share
8 answers

Of course.

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

But since Id implies that there will be no more than 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 } 
+8
source

Take a look at LINQ, you can replace it with your code: ActivityList.Any(i => i.Id == GuidToCompare);

+5
source
 foreach(var activity in ActivityList.Where(p=>p.Id == GuidToCompare)) { // Code here } 
+1
source

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

If you are looking for identifiers several times, you can create 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 create a dictionary (only works if Id is unique):

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

Another solution using Linq with Where / FirstOrDefault / Any on Id will not be more efficient than yours.

+1
source

To find all activity objects with a given GUID that you can use:

 var results = ActivityList.FindAll(item => item.ID == GuidToCompare); 
+1
source

I Havent checked this, but I'm 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
source

Just to offer you all the ways to write this request using Linq

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

Now you decide to choose a more readable fragment;)

0
source

For those who cannot use LINQ:

 List<Activity> ActivityList = new List<Activity>(); foreach (Activity activity in ActivityList.FindAll(delegate(Activity a) { return a.Id == GuidToCompare; })) { //Code here } 
0
source

Source: https://habr.com/ru/post/902832/


All Articles