2

In C# I have an object with a name and surname property and have created a list of these objects, List<person>.

I'd like to filter this List<person> basing it on a name and a surname, but in the list some person can have surname null, so I'd like to filter for name only if name is not null and for surname only if it's not null.

I'm not able to do it with findall, cause it accepts only a predicate

m_cPersons.FindAll(q => q.Name != null && q.Name.ToUpper().Contains(name)); 

How can I add two predicates?

Ralph Willgoss
  • 11,750
  • 4
  • 64
  • 67

2 Answers2

3

Instead of the List<T>.FindAll(...) method, use the LINQ Where(Func<TSource,bool> predicate) extension method:

m_cPersons.Where(q => q.Name != null && q.Name.ToUpper().Contains(name));
Ed Chapel
  • 6,842
  • 3
  • 30
  • 44
1

If I understood the question correctly, you can achieve filtering basing on name and surname with FindAll:

m_cPersons.FindAll(q =>
    (q.Name == null ||
        q.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0)
    &&
    (q.LastName == null ||
        q.LastName.IndexOf(lastName, StringComparison.OrdinalIgnoreCase) >= 0)
);

Using IndexOf(... StringComparison.OrdinalIgnoreCase) is more reliable than ToUpper().Contains(...) (see Case insensitive 'Contains(string)').

Community
  • 1
  • 1
AlexD
  • 32,156
  • 3
  • 71
  • 65