简体   繁体   中英

Filter List with object using Linq and Contains

I am trying to filter a List of users based on Surname and using Linq. I've been trying for hours and have looked at several posts that don't seem to help, hoping someone can help me understand why its not returning any results.

I have an object Users that has several properties (FirstName, Surname ect..) stored in a List. I then have a filtered list which is populated by the Linq statement,

List<User> FilteredUsers = new List<User>();
FilteredUsers.AddRange(AllUsers.Where(i => i.Surname.Contains("jones")));

This is not returning any results. I have also tried

List<User> FilteredUsers = new List<User>();
FilteredUsers.AddRange(AllUsers.FindAll(i => i.Surname.Contains("jones")));

In case you want case insensitive filtering (eg "Jones" , "jOnes" should match)

 List<User> FilteredUsers = AllUsers
   .Where(user => 
      user.Surname.IndexOf("jones", StringComparison.OrdinalIgnoreCase) >= 0))
   .ToList();

Here's my working code (adding case-insensitivity), I don't see what your problem is. Are all necessary using statements there, does the list get initialized correctly (print the content for debugging)?

using System;
using System.Linq;
using System.Collections.Generic;

public class User {
    public String Surname {get;set;}
}

static class Prog {
    static void Main() {
        List<User> AllUsers = new List<User>();
        AllUsers.Add(new User(){Surname="jones"});
        AllUsers.Add(new User(){Surname="meyer"});
        AllUsers.Add(new User(){Surname="blackjones"});
        AllUsers.Add(new User(){Surname="Jones"});
        AllUsers.Add(new User(){Surname="Jonesmith"});
        AllUsers.Add(new User(){Surname="ajonesee"});

        List<User> FilteredUsers = new List<User>();
        FilteredUsers.AddRange(AllUsers.Where(i => i.Surname.ToLower().Contains("jones")));
        foreach (User u in FilteredUsers) {
            Console.WriteLine(u.Surname);
        }
    }
}

Output:

jones
blackjones
Jones
Jonesmith
ajonesee

But I wonder why you first create an empty FilteredUsers list and then add the result instead of assigning directly:

List<User> FilteredUsers = AllUsers.Where(i => i.Surname.ToLower().Contains("jones"));

As haim770 stated it was a case sensitivity issue! Such a simple mistake! Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM