An Extensive Examination of LINQ: An Introduction to LINQ By Scott Mitchell
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int []arr = {1, 2, 3, 4, 5}; System.Console.WriteLine(arr.Where(num => num % 2 == 1).Average()); double average = (from num in arr where num % 2 == 1 select num).Average(); System.Console.WriteLine(average); } } }
Though “from num … select num” doesn’t look good – as it introduces another complexity / language – I like Where() part. (But I wonder why it is based on IEnumerable; Can’t it support any random access based algorithm or functions or predicates? Can’t it support any index in the language itself?)
In Java, there are also similar works for these kind of predicates supports both in Apache collections and Google collections. Esp., it’s worth to reading the Google Collections library code; I’d like to post some examples later.