C # basics ---- List of Linq <T>,
Recently I used List to process sorting and paging. I 'd like to write a blog record. The following describes the implementation of the Person class. The Person class has only two attributes: Name and Age.
I. List <T> sorting
1.1 List <T> provides many sorting methods, such as sort (), Orderby (), and OrderByDescending ().
LstPerson = lstPerson. orderByDescending (x => x. name ). toList (); // lstPerson = lstPerson in descending order. orderBy (x => x. age ). toList (); // ascending // lstPerson by Name and Age. sort (x, y) =>{ if (x. name. compareTo (y. name)> 0) | (x. name = y. name) & x. age> y. age) {return 1;} else if (x. name = y. name) & (x. age = y. age) {return 0;} else {return-1 ;}});
1.2 What should we do if we click the name of any column in The Silverlight datagrid recently? Maybe the first reaction is to write a sorting method for each attribute. In fact, this increases the amount of code accidentally and is not universal. In fact, reflection can be used here.
string propertityName = "Name"; lstPerson = lstPerson.OrderBy(x => { PropertyInfo[] proInfos = x.GetType().GetProperties(); return proInfos.Where(info => info.Name == propertityName).ToList()[0].GetValue(x); }).ToList();
Ii. List <T> Paging
2.1 In Silverlight, we often obtain a lot of data from the background and store it in the List <T>. However, because the interface cannot be fully displayed due to restrictions, we will think of pagination display, the first idea is to set the Size of each page in a loop. The Code is as follows:
/// <Summary> /// obtain single-page data /// </summary> /// <param name = "lstPerson"> data set </param> /// <param name = "pageIndex"> page number (starting from 1 by default) </param> /// <param name = "PageSize"> Number of data lines per page </param> /// <returns> </returns> public static List <Person> GetPage (List <Person> lstPerson, int pageIndex, int PageSize) {List <Person> pagePerson = new List <Person> (); for (int index = (pageIndex-1) * PageSize; index <pageIndex * PageSize & index <lstPerson. count; index ++) {pagePerson. add (lstPerson [index]);} return pagePerson ;}
2.2. Actually, there are skip and take methods in linq. skip indicates the number of elements skipped and take gets a specific number of elements. It seems that the code is much simpler.
public static List<Person> GetPageByLinq(List<Person> lstPerson, int pageIndex, int PageSize){ return lstPerson.Skip((pageIndex - 1) * PageSize).Take(PageSize).ToList();}
3. foreach usage of List <T>.
2.1 How can I perform the same operation on each object in the List? previously, I used to traverse through the for loop. In fact, Linq provides a convenient Foreach. Next I will + 2 for all Person ages.
lstPerson.ForEach(x => x.Age= x.Age + 2);