Holly
Holly

Reputation: 45

Searching a list to get index values in c#

I have a string comma separated list of some data. I have another list of strings of keywords that i want to search for in the first list. I want to have returned to me the index of all the elements in the first list that do no contain any of the keywords in the second list. For example:

List 1:
Student,101256,Active
Professor,597856,Active
Professor,697843,Inactive
Student,329741,Active
Student,135679,Inactive
Student,241786,Inactive

List 2:
697843
241786

My query on List 1 should be, give me all the index of all the elements that do not contain any of the elements of list 2. Therefore, the return list of indices should be 0,1,3,4. Is there any way to accomplish this?

Thanks in advance!

Edit: This is my try:

List<int> index = list1
        .Select((s, i) => new { s, i })
        .Where(e => !list2.Contains(e.s))
        .Select(e => e.i).ToList();

Upvotes: 3

Views: 493

Answers (1)

Bob Vale
Bob Vale

Reputation: 18474

You will need to reference System.Linq, this has now been edited to include the !Student filter

var list1 = new List<string> {
  {"Student,101256,Active"},
  {"Professor,597856,Active"}, 
  {"Professor,697843,Inactive"}, 
  {"Student,329741,Active"},
  {"Student,135679,Inactive"},
  {"Student,241786,Inactive"}
};
var list2 = new List<string> {{"697843"}, {"241786"}};

var result = list1
             .Select((item,i)=> new {index=i,value=item})
             .Where(item => !item.value.StartsWith("Student"))
             .Where(item => !item.value.Split(',').Any(j => list2.Contains(j)))
             .Select(item=>item.index)
             .ToList();

The first select extracts the index before filtering, the pre-edited version calculated the index after the filter and so was incorrect.

Upvotes: 1

Related Questions