Greg
Greg

Reputation: 71

Search a list by keyword

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 to the item name. How can I do this efficiently?

Upvotes: 2

Views: 1521

Answers (4)

Lawrence Wagerfield
Lawrence Wagerfield

Reputation: 6611

Following returns null if not found...

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

Upvotes: 0

Gregory A Beamer
Gregory A Beamer

Reputation: 17010

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.

Upvotes: 0

jason
jason

Reputation: 241641

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");

Upvotes: 2

Bala R
Bala R

Reputation: 108957

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

should work.

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

Upvotes: 0

Related Questions