Posts

Showing posts with the label Linq

Generic Lambda Expression to sort collections of different types

Suppose you have many collections with different types that you want to sort, of course you can do it by OrderBy or OrderByDescending extension methods but you have to specify the order criteria every time you call these methods. If the order criteria is determined in runtime, then you have to build a separate function to each order criteria of each type. To clear what I want to tell you suppose you have two classes,  Employee and Department . public class Employee { public String Name { get; set; } public Int32 Age { get; set; } public DateTime HiringDate { get; set; } } public class Department { public String DepartmentName { get; set; } public String Code { get; set; } } And you want to order the employee collection by one of its properties (Name,Age,or HiringDate) and order department collection by one of its properties. OrderBy and OrderByDescending methods need Func<TSource,TKey> as selector to compare the collection items and order them....

5 tips to get started LINQ in C#

1-LINQ is not just for Iteration : LINQ ( Language integrated Query ) is not just for queries a collection of objects, but it will be better if you think about it as a data iteration engine. If you called a method that return data of some type that you needed to convert to another datatype before passing it to another method. Assume you have a method A() that return Array of integers and you need to pass this array to method B() that accepts array of string. You should iterate over array items, one by one, to convert it.But with with LINQ you can do that with just one line of code. Int32[] nums = {23 , 45 , 65 , 23}; String[] numbers = nums.Select(i => i.ToString()).ToArray(); 2-Use the var keyword:  If you are confused about the type of the sequence result of your query and want to get your code to compile use var keyword. Your query will return an IEnumerable sequance of some type but you don't know exactly what is that type so the best cho...