开发者

Search a list by keyword

开发者 https://www.devze.com 2023-03-15 09:49 出处:网络
I am trying to search for the existence of a keyword within a list of strings. Here is what the list would look like:

I am trying to search for the existence of a keyword within a list of strings. Here is what the list would look like:

Milk, 2
Eggs, 4
Juice,1

I just want to search the list by giving a grocery list item. I only want it to search the first word in each index of the list for the grocery item name and ignore the count next t开发者_如何学Co the item name. How can I do this efficiently?


Parse the items into Dictionary<string, int> and then just lookup by key.

List<string> items = new List<string> {
    "Milk, 2",
    "Eggs, 4",
    "Juice, 1"
};
var dictionary = items.Select(s => s.Split(',')) 
                      .ToDictionary(x => x[0], x => Int32.Parse(x[1]));

bool contains = dictionary.ContainsKey("Milk");


var filteredList = groceryList.Where(i => i.Contains(searchString)).ToList()

should work.

Alternatively you can do i.StartsWith(inputString) or inputString.Equals(i.Split(",")[0]).


I like Bala's direction and it works if you want the entire line(s) the search string is found in. If you need to only get the item, you will have to Split the string.


Following returns null if not found...

string searchTerm = "Milk";
string item = items.FirstOrDefault(i => i.StartsWith(searchTerm + ","));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号