Greg
Greg

Reputation: 33

Searching a list for an index

I have a list in which i store objects with properties called Name, ID, Attendance. I want to get the index values of all the objects in the list according to a search by name. This is the easy part. Along with the search by name, i want to further narrow the index results to only those objects whose ID property is not in an exclusion list of ID's to ignore. For ex:

Exclusion List:
123
456
981

Main List of Objects
Object 1 with Name Property = Hi, ID = 123, Attendance = Present
Object 2 with Name Property = Ho, ID = 323, Attendance = Present
Object 3 with Name Property = He, ID = 456, Attendance = Present

The above are just representations of the data structures. Exclusion list is integer list and so is ID property etc. The result of my search on the Main List should return me the INDEX integer of the found object's location within the list. In this case Return should be an integer with value 1.

Thanks

Upvotes: 0

Views: 81

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500525

It sounds like you want something like:

var query = list.Select((value, index) => new { value, index })
                .Where(pair => !exclusions.Contains(pair.value.ID))
                .Select(pair => pair.index)

That will give all the matching index values; if you only want one you can use First, FirstOrDefault etc. Note that to match by name as well, you just need to extend the Where call.

If that isn't what you want, please clarify your question.

Upvotes: 3

Related Questions