C# LINQ
Sorting:
- OrderBy
- ThenBy
- OrderByDescending
- ThenByDescending
- Reverse
1 public IEnumerable<Customer> SortByName(List<Customer> cumtomerList) 2 { 3 return customerList.OrderBy(c => c.LastName) 4 .ThenBy(c => c.FirstName); 5 }
OrderBy a property that can have null value. null value will be sorted at the first.
Creating:
- Range
- Random
- Repeat
1 public IEnumerable<int> BuildIntegerSequence() 2 { 3 var integers = Enumerable.Range(0,10) //0,1,2,3,4,5,6,7,8,9 4 .Select(i => 5+(10*i)); //5, 15 ... 5 6 return integers; 7 } 8 9 public IEnumerable<string> BuildStringSequence() 10 { 11 12 var strings = Enumerable.Range(0,10) 13 .Select(i => ((char)('A'+i)).ToString()); //A,B,C,D,E,F,G,H,I 14 15 Random rand = new Random(); 16 var randomStrings = Enumerable.Range(0,10) 17 .Select(i => ((char)('A'+rand.Next(0,26))).ToString()); 18 19 return strings; 20 }
Comparing/Combining:
- Intersect
- Except
- Concat
- Distinct
- Union
1 public IEnumerable<int> CompareSequence() 2 { 3 var seq1 = Enumerable.Range(0,10); 4 var seq2 = Enumerable.Range(0, 10) 5 .Select(i => i*i); 6 7 //return seq1.Intersect(seq2); //0,1,4,9 8 //return seq1.Except(seq2); //2,3,5,6,7,8 9 //return seq1.Concat(seq2); //0,1,2,3,4,5,6,7,8,9,0,1,4,9,16,25,36,49,64,81 10 //return seq1.Concat(seq2).Distinct(); //Delete duplicates 11 return seq1.Union(seq2); //Also delete duplicates 12 }
Projection:
- Select
1 public dynamic GetNamesAndEmail(List<Customer> customerList) 2 { 3 var query = customerList.Select(c => new //Anonymous Types 4 { 5 Name = c.LastName + "," + c.FirstName, 6 c.EmailAddress 7 }); 8 return query; 9 }
- SelectMany
1 public IEnumerable<Customer> GetOverdueCustomers(List<Customer> customerList) 2 { 3 var query = customerList 4 .Select(c => c.InvoiceList //One customer has a sequence of invoices 5 .Where(i => (i.IsPaid ?? false) == false)); //return IEnumeralbe<IEnumeralbe<Inovice>> type 6 7 8 var query2 = customerList 9 .SelectMany(c => c.InvoiceList //SelectMany flatten resluting sequences into one sequence 10 .Where(i => (i.IsPaid ?? false) == false), 11 (c, i) => c); //return IEnumerable<Customer> type 12 13 }
Totaling:
- Sum
Grouping and Summing:
- GroupBy
public dynamic GetInvoiceTotalPaid(List<Invoice> invoiceList) { var query = invoiceList.GroupBy( inv => inv.IsPaid ?? false, //null as false inv => inv.TotalAmount, (groupKey, invTotals) => new //returned results of GroupBy { Key = groupKey, InvoiceAmount = invTotals.Sum() }); foreach(var item in query) { Console.WriteLine(item.Key + ": " + item.InvoiceAmount); } return query; }