C # LINQ handles list data

Source: Internet
Author: User

Read Catalogue

    • 1. GroupBy and GROUP BY
    • 2, where Condition filter.
    • 3. Select (Takes the ID column data from the list and separates it into a string by commas.) Example: 1,2,3,4,5)
    • 4, where and select the same time, take the list of ID column data, and separated into strings by commas.
    • 5. Leftist and inline (example of DataTable type)
    • 6. Sort by order
    • 7. Random Ordering
    • 8, Skip,take Paging (LINQ: Paging using take and Skip)
    • 9, distinct to heavy

Gets the list of data.

Get a list of data, model is class ilist<model> list = DAO.GETMX (model, pageInfo);
DataTable data
DataTable dt = ...;
1. GroupBy and GROUP BY
groupby//a single condition and returns the first element in the sequence that satisfies the specified condition (which is equivalent to a list of user_type, which can be more than one). List = list. GroupBy (A = A.user_type). Select (it = it). First ()). ToList ();//multiple conditions, using anonymous functions. var quary = list. Where (A = A.p_num = = "1" | | a.c_num = = "1"). GroupBy (A = new {student_id = a.student_id, User_type = A.user_type}). Select (group = new {student_id = group. key.student_id, User_type = group. Key.user_type, Count = group. Count ()});//group by//single-condition var quary = from A in list. Where (A = "1,8". Contains (A.user_type)) Group A by new {A.school} to M select new {Sch ool = M.key.school};//multi-condition var quary = from A in list. Where (A = "1,8".                Contains (A.user_type)) Group A by new {a.provice, a.school} to M select new { Provice = M.key.provice, school = m.key.school};//quary accessor method, here can write not write ToliSt ().   
After testing, the data 30W, no tolist () than ToList () Hundreds of milliseconds less time, the specific reason is unknown. Here are a few sets of data for the experiment: first 9689 9398, second 13529 10458, third 10772 10392, fourth time 11370 10833. The actual gap is not large. foreach (var item in Quary. ToList ()) {//Take value Item}
Back to top 2, where condition filter.
The provice= Jilin will be screened out. List = list. Where (x = = X.provice = = "Jilin"). ToList ();//The data containing 1, 5 criteria is filtered out, equivalent to the in usage of sql: SELECT * FROM table where User_type in (1,5) list= list. Where (A = "1,5". Contains (A.user_type)). ToList ();//here is equivalent to list= list above. Where (A = A.user_type = = "1" | | a.user_type = = "5"). ToList ();//Another form, from the beginning ilist<model> query = (from the item                      in list where ("," + Projectmodel.ids + ","). Contains ("," + Item.id + ",")                      Select item). Tolist<model> ();
Go back to Top 3, Select (Take the ID column data from the list and separate it into a string by commas.) Example: 1,2,3,4,5)
The way one//is divided into Key-value array string[] id = list. Select (A = a.id.tostring ()). ToArray ();//dt is a DataTable type that executes a LINQ statement here. AsEnumerable () is a delay that occurs, does not execute immediately, and virtually nothing happens string[] id = dt. AsEnumerable (). Select (A = a.field<int> ("id"). ToString ()). ToArray ();//Convert the array to 1,2,3,4,5 string ids = String. Join (",", id);//Mode two//effect equivalent to Foreach Loop foreach (var i in list) {    ids + = I.id + ",";} ids = IDs. TrimEnd (', '); The above code uses LINQ to filter and collate data in a dataset, as well as to filter the data in a dataset with an object-oriented mindset.
When using LINQ for DataSet Operations, LINQ cannot query directly from the DataSet object because the DataSet object does not support LINQ queries, so you need to use the AsEnumerable method to return a generic object to support query operations for LINQ: AsEnumerable () corresponds to the corresponding. AsQueryable () Difference: 1) AsEnumerable () is LINQ to Object,asqueryable () is LINQ to SQL2) AsEnumerable converts a sequence up to a IEnumerable, Forces the query operators under the enumerable class to be bound to subsequent subqueries. AsQueryable converts a sequence down to a IQueryable that generates a IQueryable wrapper for a local query. 3) AsEnumerable () deferred execution, will not be executed immediately. When you call. AsEnumerable (), nothing actually happened. When you really use objects (such as calling: First, single, ToList ...). ) is not executed. 4). ToList () Immediate execution
Back to top 4, where and select are used simultaneously, take the ID column data in the list, and separate the string into strings by commas.
string[] id = list. Where (a =!string. IsNullOrEmpty (A.user_type)). Select (A = a.id). ToArray ();//ids= "1,2,3,4,5,6,7"; string ids = String. Join (",", id);
Back to top 5, leftist and inline (example of DataTable type)
The DT,DT1,DT2 are DataTable types.
Leftist than inline, need to write more into, need to write more from the GC1 in Corr. DefaultIfEmpty (), need to write more corr=gc1.
When on is a single condition. var results = from student in dt. AsEnumerable () join user in DT1. AsEnumerable () on student. Field<int> ("student_id") equals user. Field<int> ("id")//inline join Corr in DT2. AsEnumerable () on student. Field<int> ("id") equals Corr. Field<int?> ("studentproject_id") into the corr//leftist from GC1 in Corr. DefaultIfEmpty () Select new {student, user, Corr = Gc1};//when on is multi-criteria, the use of anonymous types: In fact, and solve the idea of grouping by multi-criteria is the same. var results = from student in dt. AsEnumerable () Join ZRS in Result_zrs on new {Districtcounty = student. Field<string> ("Districtcounty"), school = student. Field<string> ("school")} equals new {Districtcounty = Zrs.districtcounty, school = Zrs.school} into ZRS from GC1 in ZRS. DefaultIfEmpty () Select new {student, Corr = GC1 };//value mode foreach (var i in results. ToList ()) {name = i.user.field<string> ("name");}
Back to top 6, sort by order
List of 1 sorts. Order BY (a = a.student_id);//2 a sort list. (A = a.student_id). ThenBy (a = a.name);//multiple sort list. (A = a.student_id). ThenBy (A = a.name). ThenBy (a = a.sex);//Parameter sort list<string> liststr = new list<string> (); liststr. ADD ("AAA"); Liststr. ADD ("BBB"); Liststr. ADD ("CCC"); liststr = Liststr. (A = a). ToList ();//aaa bbb cccliststr = liststr. (A = = = "BBB")? "1": a = = "CCC"? "2": "3"). ToList ();//BBB CCC AAA
Back to Top 7, order by random sort
Way One
Random rd = new random (); list<string> liststr = new list<string> (); liststr. ADD ("AAA"); Liststr. ADD ("BBB"); Liststr. ADD ("CCC"); Liststr. ADD ("111"); Liststr. ADD ("222"); Liststr. ADD ("333");//Random one var s = liststr. (_ = = Guid.NewGuid ()). First ();//Random two var ss = Liststr. (_ = = Guid.NewGuid ()). Take (2);//disorderly order var sss = Liststr. To-do (o = Rd. Next (0, Liststr. Count ())). ToList ();

Way Two
Random rd = new random (); list. (_=>rd. Next (1,99)). First ();//Random Sort general method
is to take an item randomly from the original list, add it to the new list, and delete it in the original list. Repeat until the original list is empty.
Note, however, that if you want to protect the original list from change, you must copy a list and then manipulate it on copy.
public static list<t> getrandomlist<t> (list<t> inputlist) { //copy to a array t[] Copyarray = New T[inputlist.count]; Inputlist.copyto (Copyarray); ADD range list<t> copylist = new list<t> (); Copylist.addrange (Copyarray); Set outputlist and random list<t> outputlist = new list<t> (); Random rd = new random (DateTime.Now.Millisecond); while (Copylist.count > 0) { //select an index and item int rdindex = Rd. Next (0, copylist.count-1); T remove = Copylist[rdindex]; Remove it from copylist and add it to output copylist.remove (remove); Outputlist.add (remove); } return outputlist;}
Back to top 8, Skip,take paging (LINQ: Using Take and Skip for paging)
Skip is the starting data that represents the beginning of the n+1 data. (Here Pagenum should start from 0)//pagenum: Number of pages, =0 is the first page, PageSize: How many lists = List of pages. Skip (Pagenum * pageSize). Take (pageSize). ToList ();//fetch top 1-10 list = list. Skip (0). Take (10). ToList ();//You can also write the top 1-10 list = list. Take (10). ToList ();//Take 第11-20条 list = list. Skip (10). Take (10). ToList ();
Back to top 9, distinct to heavy
String array string[] Idlist =  new string[]{"AAA", "BBB", "AAA"};//Remove Duplicate aaaidlist = idlist. Distinct (). ToArray ();

C # LINQ handles list data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.