Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define variables in LINQ?

Tags:

c#

linq

This code:

string[] files = {"test.txt",      "test2.txt",      "notes.txt",      "notes.doc",      "data.xml",      "test.xml",      "test.html",      "notes.txt",      "test.as"};  files.ToList().ForEach(f => Console.WriteLine(         f.Substring(             f.IndexOf('.') + 1,              f.Length - f.IndexOf('.') - 1             )     )); 

produces this list:

txt txt txt doc xml xml html txt as 

Is there some way to make f.IndexOf('.') a variable so that in more complex LINQ queries I have this defined in one place?

like image 881
Edward Tanguay Avatar asked Nov 05 '09 11:11

Edward Tanguay


People also ask

What keyword would you use to define an inline variable in a LINQ query?

C# Language LINQ Queries Defining a variable inside a Linq query (let keyword)

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

Which syntax is used in LINQ?

Most queries in the introductory Language Integrated Query (LINQ) documentation are written by using the LINQ declarative query syntax.

Can LINQ use with Array?

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


1 Answers

If you were using Linq then you could use the let keyword to define an inline variable (the code posted in the question isn't actually using Linq).

var ext = from file in files           let idx = f.LastIndexOf('.') + 1           select file.Substring(idx); 

However for the specific scenario you've posted I'd recommend using Path.GetExtension instead of parsing the string yourself (for example, your code will break if any of the files have a . in the file name).

var ext = from file in files select Path.GetExtension(file).TrimStart('.'); foreach (var e in ext) {     Console.WriteLine(e); } 
like image 142
Greg Beech Avatar answered Sep 23 '22 21:09

Greg Beech