Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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.
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();
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.