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:
- Enumerable.Where method
- List.FindAll method
- 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.
Expression, as done here . But smarter than LINQ will fail. - VladD