Home > Mobile >  Search for a value in List<Dictionary<string, object>> but using a non specific string
Search for a value in List<Dictionary<string, object>> but using a non specific string

Time:04-22

Is there is a way to search in List<Dictionary<string, object>> with a non specific string, like the LIKE OPERATION(%) in SQL and return the new List<Dictionary<string, object>>

I found this stuff, but it uses a specific string to search. Search for a value in List<Dictionary<string, object>>

For example, I have a list Dictionary like this:

List<Dictionary<string, object>> userList = new List<Dictionary<string, object>>(){
    new Dictionary<string, object>() {
        {"Id", 1},
        {"Name", "John"}
    },
    new Dictionary<string, object>() {
        {"Id", 2},
        {"Name", "Foo"}
    },
    new Dictionary<string, object>() {
        {"Id", 3},
        {"Name", "Admin"}
    },
    new Dictionary<string, object>() {
        {"Id", 4},
        {"Name", "AdminAccount"}
    },
}

If the user want to search a string "Jo", then he/she can get the first list with "John" name. But if the search string is "Admin", then first two last Dictionary will return.

Actually, this is achievable using loop. But I want to learn how to use LINQ to make my codes shorter.

CodePudding user response:

Based on the fact you want to search the values and not the keys I think you can do this using System.Linq (add that as a using statement):

var filteredList = listOfDictionaries.Where(dictionary => dictionary.Values.Any(Value => Value.ToString().Contains(search))).ToList();

However, as your dictionary has the values as type 'object' will they always have an expected string representation?

UPDATE:

If you want to search only keys of a particular type you can do this.

var searchPair = new KeyValuePair<string, string>("Name", "searchTerm");
var filteredList = listOfDictionaries.Where(dictionary => dictionary[searchPair.Key].ToString().Contains(searchPair.Value)).ToList();
  • Related