Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add an index field to Linq results

Tags:

c#

linq

Lets say I have an array like this:

string [] Filelist = ... 

I want to create an Linq result where each entry has it's position in the array like this:

var list = from f in Filelist     select new { Index = (something), Filename = f}; 

Index to be 0 for the 1st item, 1 for the 2nd, etc.

What should I use for the expression Index= ?

like image 628
Keltex Avatar asked Nov 06 '08 15:11

Keltex


People also ask

How do you find the index of an element in LINQ?

LINQ does not have an IndexOf method. So to find out index of a specific item we need to use FindIndex as int index = List. FindIndex(your condition); 0.

How do you update a record in LINQ?

You can update rows in a database by modifying member values of the objects associated with the LINQ to SQL Table<TEntity> collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL UPDATE commands.

Can LINQ query work with Array?

Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.

Can you use LINQ on a string?

LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions. For example, you can use the String.


2 Answers

Don't use a query expression. Use the overload of Select which passes you an index:

var list = FileList.Select((file, index) => new { Index=index, Filename=file }); 
like image 66
Jon Skeet Avatar answered Sep 28 '22 00:09

Jon Skeet


string[] values = { "a", "b", "c" }; int i = 0; var t = (from v in values select new { Index = i++, Value = v}).ToList(); 
like image 22
GeekyMonkey Avatar answered Sep 28 '22 02:09

GeekyMonkey