KerryL
KerryL

Reputation: 43

Get index by specific search term with a list in c#

I have a list as follows:

Cat, Green, 10
Cat, Green, 1
Dog, Red, 4
Cat, Blue, 2

Each item is just a comma seperated string element in a list.

I would like to get all the index values of all the elements in the above list that contain cat and 10 or contain cat and 2. So basically i should get the index values 0 and 3 returned from the query on the list. Can anyone show me how i can do this?

Upvotes: 0

Views: 206

Answers (2)

Rozwel
Rozwel

Reputation: 2020

One way would be to loop through the list and use string.Contains, string.StartsWith & string.EndsWith, or a Regex to test if the current item is what you are looking for. Not particularly efficient but fairly easy to write.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503839

Sounds like you want:

var query = list.Select((item, index) => new { item, index })
                .Where(pair => pair.item.Name == "Cat" && 
                               (pair.item.Value == 10 || pair.item.Value == 2))
                .Select(pair => pair.index);

(That's assuming the elements have properties of Name and Value for the first and third columns you've shown.)

EDIT: Okay, if you're just working with strings, you could use:

var query = list.Select((item, index) => new { item, index })
                .Where(pair => pair.item.StartsWith("Cat,") &&
                               (pair.item.EndsWith(", 10") || 
                                pair.item.EndsWith(", 2"))
                .Select(pair => pair.index);

Alternatively, parse the list into something a little more pleasant to start with...

Upvotes: 8

Related Questions