Usage of asp.net linq and object

Source: Internet
Author: User
Tags foreach anonymous

: What is linq?

Linq can be understood as a strongly typed query language embedded in the C # syntax. (Note: Although linq looks similar to SQL queries, its syntax is different .)

II. What is the role of linq?
Provides a unified and symmetric way for programmers to obtain data and operation data (the data here can be XML, DataSet, physical data, etc)

Query arrays

Int [] arr = new int [] {5, 1, 9, 3, 4, 0, 8 };
Var m = from item in arr
Select item;
Foreach (var item in m)
{
Response. Write (item. ToString () + "<br> ");
}
Result:

5
1
9
3
4
0
8

As you can see, the differences between LINQ and SQL are as follows:

Select is behind, which may be subject to some restrictions, so we have to put select behind.
There is a variable name in between from and data ".
Query List

System. Collections. Generic. List <int> arr = new System. Collections. Generic. List <int> {5, 1, 9, 3, 4, 0, 8 };
Var m = from item in arr
Select item;
Foreach (var item in m)
{
Response. Write (item. ToString () + "<br> ");
}

It can be seen that the query List is exactly the same as the query array. For more information, see C #3.0-set initialization settings.

Query

Dictionary

System. Collections. Generic. Dictionary <int, int> arr = new System. Collections. Generic. Dictionary <int, int> ();
Arr. Add (0, 5 );
Arr. Add (1, 1 );
Arr. Add (2, 9 );
Arr. Add (3, 3 );
Arr. Add (4, 4 );
Arr. Add (5, 0 );
Arr. Add (6, 8 );
Var m = from item in arr
Select item;
Foreach (var item in m)
{
Response. Write (item. Value. ToString () + "<br> ");
}

We can find that the query statement is the same when querying a Dictionary, but the output is no longer an item. toString (), but item. value. toString (), and we are writing "item. "," Value "will automatically appear in intelliisense, and we do not need to remember it.


Object created upon return

String [] files = System. IO. Directory. GetFiles ("C :");
Var fs = from file in files
Select new System. IO. FileInfo (file );
Foreach (var fi in FCM)
{
Response. Write (fi. Name + "" + fi. CreationTime. ToString () + "<br> ");
}

Put the files under C: In the files string array, and then "wrap" the files into a FileInfo object during the LINQ query. Note that var is used here.

Create anonymous type when returning

Int [] arr = new int [] {5, 1, 9, 3, 4, 0, 8 };
Var m = from item in arr
Select new {a = item, B = item + 1 };
Foreach (var item in m)
{
Response. Write (item. B. ToString () + "<br> ");
}

Use {}. For details, see C #3.0-anonymous type.

Use where, orderby

Int [] arr = new int [] {5, 1, 9, 3, 4, 0, 8 };
Var m = from item in arr
Where item> 3
Orderby item descending
Select item;
Foreach (var item in m)
{
Response. Write (item. ToString () + "<br> ");
}

Note that orderby is connected together, rather than order by. It is also equal to "=", rather than "= ". You may say that descending is hard to write. It is not as difficult as desc of SQL. In fact, you don't have to worry about it. Visual Web Developer and Visual Studio both have smart prompts.

 

III. What scenarios can be used by linq?
Linq to Object, Linq to XML, Linq to DataSet, Linq to Entities, and Parallel Linq (processing data returned by the linq query in Parallel)

Basic syntax of linq: var result = from item in container select item;

Obtain the data subset by using linq: var result = from item in container where booleanexpression select item;

Examples

Static void QueryStrings ()
        {
String [] games = {"Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "Shock2 "};
// Construct a query expression (note: ling expressions do not actually run the computation before the content is iterated) // No computation is performed on The linq clause.
// The result set of The linq query should always use the implicit type. In the case of a large number, the true return value implements the type of the generic IEnumerable <T> interface.
Var subset = from g in games where g. Contains ("") orderby g select g;
// The code above can also be written as IEnumerable <string> subset = from g in games where g. Contains ("") orderby g select g;
// Output the result. Computing only during iteration (this is called delayed execution)
Foreach (string s in subset)
            {
Console. WriteLine ("contains spaces: {0}", s );
            }
        }

 

 


Examples of non-iterative operations of linq:

// Perform the semi-logical operations on the semi-ach
Static void QueryInt ()
        {
// If you want to calculate the Linq expression in the foreach logical appearance, you can call an extension method with the Enumerable type definition. Such as ToArray <T> () and ToList <T>.
Int [] numbers = {2, 10, 30, 15, 1, 22 };
// Obtain data immediately
Int [] rst = (from I in numbers where I> 10 orderby I select I). ToArray <int> ();

        }

 

 


Common functions
1. count <T> () gets the number of items returned by the linq query expression.

Static void FunLinq ()
        {
Int [] numbers = {2, 10, 30, 15, 1, 22 };
// The total number of outputs greater than 10
Int count = (from I in numbers where I> 10 orderby I select I). Count <int> ();
Console. WriteLine (count); // output: 3
        }

 

 


2. Reverse <T> reverses the items in the linq result set.

Var newnumbers = from I in numbers select I;
Foreach (var p in numbers. Reverse ())
            {
Console. WriteLine (p); // output 22 1 15 30 10 2
            }

 

 


3. orderby: sorts the data in linq. The default value is positive.

// Sort (forward)
String [] games = {"Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "Shock2 "};
Var newn = from I in games orderby I ascending select I;
Foreach (var p in games)
            {
Console. Write (p + ",");//
            }

 


4. Distinct () remove duplicate items from data // sort (forward)

String [] games = {"Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "Shock2", "Shock2 "};
Var newn = from I in games orderby I ascending select I;
Foreach (var p in games. Disinct ())
            {
Console. Write (p + ",");//
            }

 


5. Aggregate operations

 

// Aggregation


// Maximum value
Var maxi = (from I in games orderby I ascending select I). Max ();
// Minimum value
Var mini = (from I in games orderby I ascending select I). Min ();
// Average value
Var avar = (from I in numbers orderby I ascending select I). Average ();
// Sum
Var sum = (from I in numbers orderby I ascending select I). Sum ();
Related Article

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.