IEnumerable.Select with index

I have the following code:

var accidents = text.Skip(NumberOfAccidentsLine + 1).Take(numberOfAccidentsInFile).ToArray(); 

where the crash is an array of strings.

I want to convert Linq from a string array to an array of Accident objects as follows:

  return accidents.Select(t => new Accident() {Id = i, Name = t.Replace("\"", string.Empty)}).ToArray(); 

How to get index i from an array of crashes using linq or do i need to go to an old school?

+6
source share
3 answers

I'm not sure which index you are looking for, but if it's just a set of consecutive numbers, you're in luck. There is a Select overload that does just that:

 return accidents.Select((t, i) => new Accident() {Id = i, Name = t.Replace("\"", string.Empty)}).ToArray(); 

He expects the delegate to take two parameters - the element and its index.

+13
source

Use Enumerable.Range to generate identification values, and then use the current value to index into your array of strings:

 Enumerable.Range(0, accidents.Length).Select(f => new Accident() { Id = f, Name = accidents[f] }) 
+1
source

Maybe this LINQ query will help you find a formatted name with an index:

 var accidents=(from acc in accidents select new { id=accidents.IndexOf(acc), Name = acc.Replace("\"", string.Empty) }).ToArray() 

or you can also use .ToList() for the case if you want the result to be in IEnumerable format.

0
source

Source: https://habr.com/ru/post/979082/


All Articles