Find() vs. Where().FirstOrDefault()

Where is the Find method on IEnumerable<T>? (Rhetorical question.) The Where and FirstOrDefault methods are applicable against multiple kinds of sequences, including List<T>, T[], Collection<T>, etc. Any sequence that implements IEnumerable<T> can use these methods. Find is available only for the List<T>. Methods that are generally more applicable, are then more reusable and have a … Read more

How can I get LINQ to return the object which has the max value for a given property? [duplicate]

This will loop through only once. Item biggest = items.Aggregate((i1,i2) => i1.ID > i2.ID ? i1 : i2); Thanks Nick – Here’s the proof class Program { static void Main(string[] args) { IEnumerable<Item> items1 = new List<Item>() { new Item(){ ClientID = 1, ID = 1}, new Item(){ ClientID = 2, ID = 2}, new … Read more

Code equivalent to the ‘let’ keyword in chained LINQ extension method calls

Let doesn’t have its own operation; it piggy-backs off of Select. You can see this if you use “reflector” to pull apart an existing dll. it will be something like: var result = names .Select(animalName => new { nameLength = animalName.Length, animalName}) .Where(x=>x.nameLength > 3) .OrderBy(x=>x.nameLength) .Select(x=>x.animalName);

Sorting a list using Lambda/Linq to objects

This can be done as list.Sort( (emp1,emp2)=>emp1.FirstName.CompareTo(emp2.FirstName) ); The .NET framework is casting the lambda (emp1,emp2)=>int as a Comparer<Employee>. This has the advantage of being strongly typed. If you need the descending/reverse order invert the parameters. list.Sort( (emp1,emp2)=>emp2.FirstName.CompareTo(emp1.FirstName) );

Dynamic LINQ OrderBy on IEnumerable / IQueryable

Just stumbled into this oldie… To do this without the dynamic LINQ library, you just need the code as below. This covers most common scenarios including nested properties. To get it working with IEnumerable<T> you could add some wrapper methods that go via AsQueryable – but the code below is the core Expression logic needed. … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)