LINQ : Standard Query Operators

LINQ : Standard Query Operators

1 > Filtering
Filtering operators define a restriction to the elements returned with the Where query operator you can use a predicate, for example defiend by a Lambda expression that returns a bool OfType<T> filters the elements based on the type and returns only the elements of the type T.

string[] names = { "Tom""Dick""Harry""Mary""Jay" };

IEnumerable<string> query =
       names.Where (name => name.EndsWith ("y"));

query = from n in names
        where n.EndsWith ("y")
        select n;

Using multiple where clauses

var names = new[] { "Tom""Dick""Harry""Mary""Jay" }.AsQueryable();

var query =
       from n in names
       where n.Length > 3
       let u = n.ToUpper()
       where u.EndsWith ("Y")
       select u;

2 > Projection

Projection operators are used to transform an object into a new object of a different type. Select and SelectMany define a projection to select values of the result based on a selector function.

1>  var query =      from f in FontFamily.Families
       select f.Name;


using (var Context = new MyEntities())

            var UDetail = (from u in Context.Users
                           where u.UserID == UId
                           select new
            if (UDetail.Count > 0)
// Some Code Here

3 > Sorting

Sorting operators change the order of elements returned. OrderBy sorts values in ascending order, OrderByDescending sorts values in descending order. ThenBy and ThenByDescending operators are used for a secondary sort if the first sort gives similar results. Reverse reverses the elements in collection.

using (var Context = new MyEntities())
var UserOrderBy = Context.Users.Where(c=>c.UserID==UserID).OrderBy(c=>c.UserID);
var UserOrderByDesc = Context.Users.Where(c=>c.UserID==UserID).OrderByDescending(c=>c.UserID);
var UserThenBy = Context.Users.Where(c=>c.UserID==UserID).OrderBy(c=>c.UserID).ThenBy(c=>c.UserID);
var UserThenByDesc = Context.Users.Where(c=>c.UserID==UserID).OrderByDescending(c=>


4 > Join

Join operators are used to combine collections that might not be directly related to each other. With the join operator a join of two collections based on key selector functions can be done. This is similar to the JOIN you know from SQL. The GroupJoin operator joins two collections and groups the results.

using (var Context = new MyEntities())

            var UDetail = (from r in Context.UserInRoles
                           join u in Context.Users on r.UserID equals u.UserID
                           where r.RoleID == RoleID
                           select new
            if (UDetail.Count > 0)

5 > Grouping

Grouping operators put the data into groups. The GroupBy operator groups elements with a common key.

string[] files = Directory.GetFiles(Path.GetTempPath()).Take(100).ToArray();

files.GroupBy(file => Path.GetExtension(file));

6 > Quantifier

Quantifier operators return a Boolean value if elements of the sequence satisfy a specific condition. Any, All, and Contains are quantifier operators. Any determines if any element in the collection satisfies a predicate function. All determines if all elements in the collection satisfy a predicate. Contains checks whether a specific element is in the collection. These operators return a Boolean value

new int[] { 234 }.Contains (3);
new int[] { 234 }.Any (n => n == 3);
new int[] { 234 }.Any (n => n > 10);
new int[] { 234 }.Where (n => n > 10).Any();

Customers.Where (c => c.Purchases.All (p => p.Price < 100))

7 > Partitioning

Partitioning operators return a subset of the collection. Take, Skip, TakeWhile, and SkipWhile are partitioning operators. With these, you get a partial result. With Take, you have to specify the number of elements to take from the collection, Skip ignores the specified number of elements and takes the rest. TakeWhile takes the elements as long as a condition is true.

string[] typeNames =
       (from t in typeof (int).Assembly.GetTypes() select t.Name).ToArray();

       .Where   (t => t.Contains ("Exception"))
       .OrderBy (t => t)
       .Skip (20)
       .Take (20);

int[] numbers = { 35223441 };

numbers.TakeWhile (n => n < 100);
numbers.SkipWhile (n => n < 100);

8 > Set

Set operators return a collection set. Distinct removes duplicates from a collection. With the exception of Distinct, the other set operators require two collections. Union returns unique elements that appear in either of the two collections. Intersect returns elements that appear in both collections. Except returns elements that appear in just one collection.

int[] seq1 = { 123 }, seq2 = { 345 };

seq1.Union (seq2);

9 > Element

Element operators return just one element. First return the first element that satisfies a condition. ForstOrDefault is similar to First, but it returns a default value of the type if the element is not found. Last returns the last element that satisfies a condition. With ElementAt, you specify the position of the element to return. Single returns only the one element that satisfies a condition. If more than one element satisfies the condition, an exception is thrown.

int[] numbers  = { 12345 };

numbers.Single (n => n % 3 == 0);
numbers.SingleOrDefault (n => n % 2 == 0);
numbers.ElementAt (9);
numbers.ElementAtOrDefault (9)

10 > Aggregate

Aggregate operators compute a single value from a collection. With aggregate operators, you can get the sum of all values, the number of all elements, the element with the lowest or highest value an average number, and so on.

new int[] { 567 }.Count();
"pa55w0rd".Count (c => char.IsDigit (c));

int[] numbers = { 283214 };

numbers.Aggregate (0, (seed, n) => seed + n);

numbers.Max (n => n % 10)

11 > Conversion

Conversion operators convert the collection to an array: IEnumerable, IList, IDictionary, and so on.

ArrayList cList = new ArrayList();
cList.AddRange ( new int[] { 345 } );

DateTime offender = DateTime.Now;
cList.Add (offender);

       ofTypeSequence = cList.OfType<int>(),
       castSequence = List.Cast<int>();

string[] toArray = query.ToArray();
List<string> toList = query.ToList();

Dictionary<intstring> idToName = Customers.ToDictionary (c => c.ID, c => c.Name);

12 > Generation

Generation operators return a new sequence. The collection is empty using the Empty operator, Range returns a sequence of numbers, and Repeat returns a collection with one repeated value.

int[][] numbers =
  new int[] { 123 },
  new int[] { 456 },
  null                     // this null makes the query below fail.

IEnumerable<int> flat = numbers
       .SelectMany (innerArray => innerArray ?? Enumerable.Empty <int>() );

Enumerable.Range (55);
Enumerable.Repeat (53);

Next Recommended Reading Using LINQ's Zip query operator