简体   繁体   中英

Need help understanding .Select method C#

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!

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);

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. Eg 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()
            };

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM