user3442470 user3442470 - 1 year ago 89
C# Question

LINQ - search between IList and list of strings

Im not very well versed in LINQ and I think this problem could be solved with it.

I have a list of objects:

IList<Aclass> allADs;


public static class Aclass
private string myName { get; set; }
//And more attributes.

And I have a list of strings:

List<string> lstGroups = new List<string>();

At this point in my code both my list of objects and the list of strings are full. What I want is a list of
that matches the property
with the strings of the list. the list of strings have unique elements, there is no repetition.

Answer Source

Use Contains:

var res = lstAclass.Where(a => lstGroups.Contains(a.MyName)).ToList();

When lstAclass has lots of elements, you can speed up the search by constructing a HashSet of group names prior to running this query:

var setGroups = hew HashSet<string>(lstGroups);
var res = lstAclass.Where(a => setGroups.Contains(a.MyName)).ToList();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download