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?
C# Language LINQ Queries Defining a variable inside a Linq query (let keyword)
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.
Most queries in the introductory Language Integrated Query (LINQ) documentation are written by using the LINQ declarative query syntax.
Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With