I have a List, where T is a class object with a set of fields of type String. I need to filter this list by one of the fields of the object, taking into account the fact that the values ​​for filtering are 2 and more. I found a simple way: foreach under the list Question:

  • Is there a more elegant (for example through LINQ to List)?
  • If the list is large and there are many fields, what will work faster?
  • one
    If you really need to quickly and to suffer, you can compile Expression , as done here . But smarter than LINQ will fail. - VladD

2 answers 2

Suppose you have a class like this:

 public class SuperClass { public string One { get; set; } public string Two { get; set; } public string Three { get; set; } } 

Create a list of objects of our class and add a few elements:

 var lst = new List<SuperClass>(); lst.Add(new SuperClass() { One = "1", Two = "2", Three = "3" }); // first lst.Add(new SuperClass() { One = "11", Two = "2", Three = "33" }); // second lst.Add(new SuperClass() { One = "111", Two = "222", Three = "3" }); // third 

I'll suggest this filtering method via LINQ using Where :

 var onlyTwo = lst.Where(x => x.Two == "2"); // first, second var twoAndThree = lst.Where(x => x.Two == "2" && x.Three == "3"); // first var twoOrThree = lst.Where(x => x.Two == "2" || x.Three == "3"); // first, second, third 

You can also use the method from List<T> , using FindAll :

 var onlyThree = lst.FindAll(x => x.Three == "3"); // first, third 

Useful links to explore:

  1. Enumerable.Where method
  2. List.FindAll method
  3. LINQ query expressions

Regarding what will be faster: I think LINQ will be fast enough, FindAll returns a new collection, so I think it will be slower, but going through the foreach with internal checking and adding to the new list will most likely be the slowest. If I am mistaken in speed, then I do not mind if I was corrected. In any case, you can always check what will work faster.

  • The LINQ methods, as well as FindAll are called delegates - this is an extra overhead. So foreach or for will be faster (although, depending on how you write), but longer. - Alexander Petrov
  • FindAll in its structure is similar to LINQ of the following form: Where(...).ToList() , and a new collection is returned, so I assumed that just Where will be faster. But foreach or for can actually be faster, but it depends on how simple they are. - Denis Bubnov 2:41

Option with LINQ to Objects:

 var list = Process.GetProcesses(); var filters = new[] { "chrome", "notepad" }; var results = from item in list where filters.Contains(item.ProcessName, StringComparer.InvariantCulture) select item; 

The speed and elegance of the code often do not overlap. The for loop and the hash table instead of string[] for filters will work faster if the list is not very large. If the list is large, it makes sense to parallelize using TPL and PLINQ .