LINQ in C# - Examples - Select - Projection

Select - Type 1 - Example -1

string[] presidents = { "Adams",   // index 0
                                    "Arthur",  // index 1
                                    "Buchanan",// index 2
                                    "Bush",};  // index 3

            IEnumerable<string> sequence = presidents.Select(p=> p.ToUpper()); 

            foreach (var item in sequence)
                Console.WriteLine(item);
//Output
ADAMS
ARTHUR
BUCHANAN
BUSH

Select - Type 1 - Example -2

string[] presidents = { "Adams",   // index 0
                                    "Arthur",  // index 1
                                    "Buchanan",// index 2
                                    "Bush",};  // index 3

            var sequence = presidents.Select(p=> new { p, p.Length }); 

            foreach (var item in sequence)
                Console.WriteLine(item);
//Output
{ p = Adams, Length = 5 }
{ p = Arthur, Length = 6 }
{ p = Buchanan, Length = 8 }
{ p = Bush, Length = 4 }

Select - Type 1 - Example -3

string[] presidents = { "Adams",   // index 0
                                    "Arthur",  // index 1
                                    "Buchanan",// index 2
                                    "Bush",};  // index 3

            var sequence = presidents.Select(p=> new { Name = p, Name_length=  p.Length }); 

            foreach (var item in sequence)
               Console.WriteLine("{0} length is {1}",item.Name, item.Name_length);
//Output
Adams length is 5
Arthur length is 6
Buchanan length is 8
Bush length is 4

Select - Type 2 with index - Example -1

string[] presidents = { "Adams",   // index 0
                                    "Arthur",  // index 1
                                    "Buchanan",// index 2
                                    "Bush",};  // index 3

            var sequence = presidents.Select((p, i)=> new { index = i, Name = p, Name_length=  p.Length });  //i is the index of the element

            foreach (var item in sequence)
              Console.WriteLine("{2}.{0} length is {1}",item.Name, item.Name_length, item.index+1);
//Output
1.Adams length is 5
2.Arthur length is 6
3.Buchanan length is 8
4.Bush length is 4

No comments:

Post a Comment

Framework Fundamentals - String - Comparing Strings

In comparing two values, the .NET Framework differentiates the concepts of equality comparison and order comparison . Equality compariso...