0

I am having difficulties understandting what type of statement this is and how to use the .select method.

 var lines = System.IO.File.ReadLines(@"c:\temp\mycsvfil3.csv")
           .Select(l => new
           {
               myIdentiafication= int.Parse(l.Split(',')[0].Trim()),
               myName= l.Split(',')[1].Trim()
           }
             ).OrderBy(i => i.Id);

any help is appreciated!

3 Answers3

2

This is a LINQ query. Enumerable.Select projects each line from file into anonymous object with properties myIdentiafication and myName. Then you sort sequence of anonymous objects with Enumerable.OrderBy. But you should select property which exists in anonymous object. E.g. myIdentiafication because there is no id property:

var lines = File.ReadLines(@"c:\temp\mycsvfil3.csv") // get sequence of lines
                .Select(l => new {
                    myIdentiafication = int.Parse(l.Split(',')[0].Trim()),
                    myName= l.Split(',')[1].Trim()
                 }).OrderBy(i => i.myIdentiafication);

NOTE: To avoid parsing each line twice, you can use query syntax with introducing new range variables:

var lines = from l in File.ReadLines(@"c:\temp\mycsvfil3.csv")
            let pair = l.Split(',')
            let id = Int32.Parse(pair[0].Trim())
            orderby id
            select new {
                Id = id,
                Name = pair[1].Trim()
            };
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
2

The Enumerable.Select method is an extension method for an IEnumerable<T> type. It takes a Func<TSource, TResult> that allows you to take in your IEnumerable<T> items and project them to something else, such as a property of the type, or a new type. It makes heavy use of generic type inference from the compiler to do this without <> everywhere.

In your example, the IEnumerable<T> is the string[] of lines from the file. The Select func creates an anonymous type (also making use of generic type inference) and assigns some properties based on splitting each line l, which is a string from your enumerable.

OrderBy is another IEnumerable<T> extension method and proceeds to return an IEnumerable<T> in the order based on the expression you provide.

T at this point is the anonymous type from the Select with two properties (myIdentiafication and myName), so the OrderBy(i => i.Id) bit won't compile. It can be fixed:

.OrderBy(i => i.myIdentiafication);
Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
  • Thanks that does help me understand it much better and @ Sergey thinking of it as a db query makes it much simpler for me. –  Mar 13 '14 at 16:32
0

From each string returned by ReadLines create an anonymous object with two properties (myIdentiaficiation and myName). Within the Select the context variable l represents a single line from the set returned by ReadLines.

Craig W.
  • 17,838
  • 6
  • 49
  • 82