[Linq] common grammar summary

Posted by saurabhdutta on Thu, 02 Apr 2020 01:24:19 +0200

Language integrated query (LINQ), which integrates query syntax in C programming language, can access different data sources with the same syntax. LINQ provides the abstraction layer of different data sources, so the same syntax can be used.

public class Book
{
    public int Id { get; set; }
    /// <summary>
    /// Title
    /// </summary>
    public string BookName { get; set; }
    /// <summary>
    /// author id
    /// </summary>
    public int AutherId { get; set; }
    /// <summary>
    /// type
    /// </summary>
    public string Type { get; set; }
    /// <summary>
    /// price
    /// </summary>
    public decimal Price { get; set; }
    /// <summary>
    /// Sales volume
    /// </summary>
    public int Sales { get; set; }
}
public class Auther
{
    public int Id { get; set; }
    /// <summary>
    /// author
    /// </summary>
    public string AutherName { get; set; }
}
public class Library
{
    public string Address { get; set; }
    /// <summary>
    /// Book
    /// </summary>
    public List<Book> BookList { get; set; }
}

1. Condition query (Where)

 var query = from book in bookList
             where book.Price > 50
             orderby book.Sales descending,book.BookName
             select book;
//Equate to
var query = bookList.Where(n => n.Price > 50).OrderByDescending(g => g.Sales).ThenBy(y => y.BookName);

It should be noted that query delay

var ary = new List<string>(){ "Aa", "Bb", "Cc"};

var a1 = ary.Where(n => n.Contains("a"));//["Aa"]

ary.Add("Ga");

a1;//["Aa", "Ga"]

To solve this problem, you only need to use ToList();

var ary = new List<string>(){ "Aa", "Bb", "Cc"};

var a1 = ary.Where(n => n.Contains("a")).ToList();//["Aa"]

ary.Add("Ga");

a1;//["Aa"]

Index filtering

//Sales volume greater than 50 and odd lines
var query = bookList.Where((n, index) => n.Sales > 50 && index%2 != 0);

2. Composite query (SelectMany)

//Find all the novels in the library
var query = from library in libraryList
            from book in library.BookList
            where book.Type == "Novel"
            select book;

//Equate to
query = libraryList.SelectMany(n => n.BookList).Where(g => g.Type == "Novel");

//Organization return results
query = libraryList.SelectMany(n => n.BookList,  (n, g) => new {n.Address, g.BookName, g.Sales}).Where(y => y.Sales > 100);

3. Collection connection

//Internal connection
var query1 = from book in bookList
         join auther in autherList on book.AutherId equals auther.Id
         select new { book.BookName, auther.AutherName };
//Group connection
var query2 = from auther in autherList
           join book in bookList on auther.Id equals book.AutherId into items
           select new { auther.AutherName, Books = items };
//Left outer join
var query3 = from book in bookList
            join auther in autherList on book.AutherId equals auther.Id into items
            from auther in items.DefaultIfEmpty()
            select new
            {
                book.BookName,
                AutherName = auther == default(Auther) ? "nothing" : auther.AutherName
            };
//Multi conditional connection
var query4 = from book in bookList
    join auther in autherList on new {name = book.BookName, id = book.AutherId} equals new {name = auther.AutherName, id = auther.Id}
    select book;

4. Sort (OrderBy, ThenBy)

var query = from book in bookList
                orderby book.Sales descending, book.AutherId, book.Price descending 
                select book;
//Equate to
query = bookList.OrderByDescending(n => n.Sales).ThenBy(g => g.AutherId).ThenByDescending(y => y.Price);

5. Group by

//Single conditional grouping
var query = from book in bookList
                        group book by book.Type into bs
                        select bs.First();
//Equate to
query = bookList.GroupBy(n => n.Type).Select(g => g.First());

//Multi conditional grouping
var query = from book in bookList
            group book by new { book.Type, book.AutherId } into bs
            select new
            {
                Type = bs.First().Type,
                AutherId = bs.First().AutherId,
                Count = bs.Count()
            };
//Equate to
query = bookList.GroupBy(n => new {n.Type, n.AutherId}).Select(g => new
            {
                Type = g.First().Type,
                AutherId = g.First().AutherId,
                Count = g.Count()
            });

6. Merge and partition (Zip, Take, Skip)

int[] numbers = { 1, 2, 3 };
string[] words = { "One", "Two", "Three", "Four" };
//Elements are combined in turn, and the set with smaller length
IEnumerable<string> zip = numbers.Zip(words, (n, g) => n + "=" + g);//["1=One", "2=Two", "3=Three"]

//Skip before collection n Element
var skip = words.Skip(3);//["Four"]
//Before getting the collection n Element,There is delay.
var take = numbers.Take(2);//[1, 2]

int pageSize = 3;//Capacity per page
int pageNum = 0;//The number of pages
var page = words.Skip(pageSize * pageNum).Take(pageSize);//["One", "Two", "Three"]

7. Set operations (Distinct, Union, Concat, Intersect, Except)

int[] ary1 = {1, 2, 2, 4, 5};
int[] ary2 = {3, 5, 5, 6, 10, 7};

//merge,Automatic weight removal
var union = ary1.Union(ary2);//1, 2, 3, 4, 5, 6, 7, 10
//merge,Won't go heavy.
var concat = ary1.Concat(ary2);//1, 2, 2, 4, 5, 3, 5, 5, 6, 10, 7
//Duplicate removal
var distict = ary1.Distinct();//1, 2, 4, 5
//intersect,Automatic weight removal
var intersect = ary1.Intersect(ary2);//5
//Complement set,Automatic weight removal
var except = ary1.Except(ary2);//1, 2, 4

8. Type filtering (ofType)

object[] data = { "one", 1 , 2 ,"three"};
var query = data.ofType<string>();

9. Aggregate operators (Count, Sum, Min, Max, Average, aggregate)

//Number
var count = bookList.Count(n => n.Sales > 50);
//Summation
var sum = bookList.Sum(n => n.Price);
//minimum value
var min = bookList.Min(n => n.Sales);
//Maximum value
var max = bookList.Max(n => n.Price);
//average value
var average = bookList.Average(n => n.Sales);
//accumulation,Total sales volume
var aggregate1 = bookList.Select(n => n.Sales).Aggregate((g, y) => g + y);
//Accumulation, initial value
var aggregate2 = bookList.Select(n => n.Sales).Aggregate(10, (g, y) => g + y);
//Accumulation, initial value, result processing
var aggregate3 = bookList.Select(n => n.Sales).Aggregate(10, (g, y) => g + y, result => result/100);

10. Conversion operators (ToArray, ToDictionary, ToList, ToLookup, Cast)

Book[] ary = bookList.ToArray();

List<Book> list = bookList.ToList();

Dictionary<int, Book> dic = bookList.ToDictionary<Book, int>(n => n.Id);

//convert to LookUp aggregate,key-with key Internal set of groups
ILookup<string, Book> look = bookList.ToLookup(n => n.Type);

IEnumerable<Book> cast = ary.Cast<Book>();

Topics: C# Programming