Home > Enterprise >  Get value from List based on match condition
Get value from List based on match condition

Time:11-02

I have a list : var abc = {"Apple", "Orange"};

I also have a string : var def = "{[Mountain, Mountain, Apple ]}";

I am able to check if the value is true or false with the below code

bool ghi = abc.Any(s => def.Contains(s));

How do I get the position or index in abc though ?

CodePudding user response:

You can eiher implement for loop or put something like this:

int index = Enumerable
  .Range(0, abc.Count)
  .FirstOrDefault(i => def.Contains(abc[i]), -1);

Or even less readble but works with IEnumerable<string> not necessary List<string>:

int index => abc
   .Select((item, idx) => (item, idx))
   .FirstOrDefault(pair => def.Contains(pair.item), (null, -1))
   .idx;

CodePudding user response:

Typically, you would NOT ask for the position. Instead, you want the elements, which you can do like this:

var result = abc.Where(s => def.Contains(s));

Now result has the items (all of them) that match.

  •  Tags:  
  • c#
  • Related