LINQ Learning Experience sharing------(iii) LINQ grammar detailed 2

Source: Internet
Author: User

And then, in this section, I'm going to lead you through the rest of the LINQ syntax. OK, no more nonsense, get to the point.

1, Cast, oftype operator

Cast and OfType: are used to convert a collection object of type IEnumerable to a collection object of type ienumerable<t>, the function of which is the same, the only difference being that the cast operator does the type conversion If the transformation fails in the conversion, an exception is thrown, and the oftyoe operator simply converts the elements that can be converted.

Here's an example from the previous section: (This example is referenced from Rookie_j blog)

Create a new ArrayList object first

ArrayList ArrayList = new ArrayList ()

{

New Person () {name= "Olive", sex= "female", age=18},

New Person () {name= "Moyao", sex= "male", age=19},

New Person () {name= "Momo", sex= "female", age=20},

New Person () {name= ' only ', sex= ' female ', age=21},

New Profession () {Name = "Olive", Zhiye = "Accounting"},

New Profession () {Name = "Remote", Zhiye = "IT coder"},

New Profession () {Name = "Blove", Zhiye = "Student"},

New Profession () {name= "afor", zhiye= "writer"}

};

Console.WriteLine ("Personnel Information table:");

Convert a ArrayList object to a Ienumerable<person> object

Ienumerable<person> pers= ArrayList. Oftype<person> ();

foreach (var p in Pers)

{

Console.WriteLine ("Personnel Information:" +p.name+ "Sex:" +p.sex+ "Age:" +p.age);

}

Console.WriteLine ("Personnel occupation Table:");

Will ArrayList

ienumerable<profession> professions = ArrayList. Oftype<profession> ();

foreach (var p in professions)

{

Console.WriteLine ("Person Name:" + p.name + "Occupation:" + P.zhiye);

}

Results:

2, DefaultIfEmpty, FirstOrDefault, LastOrDefault, Singleordefault, Elementatordefault

2.1. DefaultIfEmpty: Returns a sequence containing the default elements when the query does not meet the required information

Ienumerable<person> pers= ArrayList. Oftype<person> ();

var defaulttest = pers. Where (p => p.name = = "Snow"). DefaultIfEmpty (new person () {Name = "no Man Found"});

foreach (var p in defaulttest)

{

Console.WriteLine ("Query Result:" + p.name);

}

Results:

2.2, Firstordefault/lastordefault: As the name suggests, returns the first (last) element of the output sequence that satisfies the condition, if not, the sequence element type is a reference type, then returns NULL, and the value type returns the default value of the value type.

Person defaulttest = pers. Where (p => p.name = = "Olive"). FirstOrDefault ();

foreach (var p in defaulttest)

//{

if (defaulttest!= null)

{

Console.WriteLine ("FirstOrDefault Query Result:" + Defaulttest.name + "" + Defaulttest.age + "" +defaulttest.sex);

}

Else

{

Console.WriteLine ("FirstOrDefault query result: No such person.") ");

}

Results:

If the person defaulttest = pers. Where (p => p.name = = "Snow"). FirstOrDefault ();

The result is:

The LastOrDefault and FirstOrDefault use methods are basically the same, except that LastOrDefault returns the last element of a sequence that matches the criteria of the query, and returns the default value if no qualifying element is available.

2.3, Singleordefault: a bit similar to FirstOrDefault, if there is no element to return a default value (T), but if there are more than one element, the Singleordefault operator will still throw an exception

For example:

Person defaulttest = pers. Where (P => p.sex== "male"). Singleordefault ();

Result: This exception occurred because there are multiple eligible information found.

Person defaulttest = pers. Where (P => p.name= "Olive"). Singleordefault ();

Results:

2.4, Elementatordefault: Used to return the elements specified in the sequence, if the value of the specified index is not valid, then return a dependent type default value element

Example: Person defaulttest = pers. Where (p => p.sex = = "female"). Elementatordefault (5);

if (defaulttest!= null)

{

Console.WriteLine ("Elementatordefault Query Result:" + Defaulttest.name + "" + Defaulttest.age + "" + defaulttest.sex);

}

Else

{

Console.WriteLine ("Elementatordefault query result: No such person.") ");

}

Results:

3, Range,repeat

Both of these methods are static methods of the enumerable class under the System.Linq.Enumerable namespace, but are not extension methods, which are used as follows:

3.1, Range: can only produce an integer sequence, and generated a sequential sequence

Var Rangetest=enumerable.range (115,6);

Foreach (Var r in Rangetest)

{

Console.WriteLine ("Generate sequence element:" +r);

}

Results:

3.2, Repeat: Can produce duplicate of the generic sequence

var var repeattest = enumerable.repeat ("Olive", 6);//function parameters: 1, elements to repeat, 2, number of repetitions

var rangetest = Enumerable.range (115, 6);

foreach (Var r in Repeattest)

{

Console.WriteLine ("Repeat generates sequence elements:" +r);

}

Results:

3. Delayed execution

Deferred execution: The query variable itself simply stores the query command and does not save the query result, and the actual query execution is deferred until the query variable is cycled through the foreach statement.

var serachtest = from P in pers

where p.sex = "female"

Select P;

foreach (var p in serachtest)

{

Console.WriteLine ("Personnel Information:" + p.name + "Sex:" + P.sex + "Age:" + p.age);

}

Results:

Written here, perhaps everyone has not yet understood what is execution. Of course, I did not understand when I was studying.

Let's look at the following example

int[] Yanchishuzu = new int[] {1, 2, 3, 4, 5};

var Yuan = Yanchishuzu. Select (y => y);

foreach (int i in Yuan)

{

Console.WriteLine (i);

}

Yanchishuzu[0] = 116;

YANCHISHUZU[1] = 116;

YANCHISHUZU[2] = 116;

YANCHISHUZU[3] = 116;

YANCHISHUZU[4] = 116;

foreach (int i in Yuan)

{

Console.WriteLine (i);

}

Results:

Execute the following code:

int[] Yanchishuzu = new int[] {1, 2, 3, 4, 5};

var Yuan = Yanchishuzu. Select (y => y). ToList ();

foreach (int i in Yuan)

{

Console.WriteLine (i);

}

Yanchishuzu[0] = 116;

YANCHISHUZU[1] = 116;

YANCHISHUZU[2] = 116;

YANCHISHUZU[3] = 116;

YANCHISHUZU[4] = 116;

foreach (int i in Yuan)

{

Console.WriteLine (i);

}

Results:

From the results of two experiments: the first two times after the results are not the same, but also said above. "The query variable itself simply stores the query command, do not save query results, here is a good embodiment of the first query after the data source has been updated, so the second query, the data source has changed, so the results of the query is not the same, this way of execution called" deferred query ", The actual query execution is deferred until the query variable is cycled through the foreach statement, so you can react immediately when the data source changes.

The result of the second experiment two times is the same, because there is a tolist () method behind the query statement, which is executed immediately, followed by a int[collection to cache the object instead of the Ienumerable<int> collection object. Even if the data source is reset at this time, the object of the Foreach execution loop is the original object, so the result will not change.

After these explanations, do you have a new understanding of this? Isn't it a little clear? The following is a list of the common methods of LINQ queries, from which you can clearly see what is delayed and what is not. This allows you to use this feature to update the display data in real time.

The

Where

Filter; delay

Select

/td>

Select; delay

Distinct

Query non-duplicate result set; delay

Count

Returns the number of elements in the collection, returning the int type; no delay

LongCount

Returns the number of elements in the collection, returns a long; no delay

Sum

Returning a numeric type element in a collection Motonosuke and, the collection should be an int type collection;

min

Returns the minimum value of the elements in the collection; no delay

Max

To return the maximum value of the elements in the collection; no delay

Average

Returns the average of the numeric type elements in the collection. The collection should be a collection of numeric types whose return value type is double;

Aggregate

To get the aggregate value based on the expression entered; no delay

4. Non-delay Execution (Tolist,toarray,todictionary,sequenceequal,first,last,single,any,all,contains)

4.1, Tolist/toarray

ToList: Used to convert an input sequence to a type List<t> collection object

ToArray: Generates and returns an array of element type T

The two functions are similar, and the upper part, when it comes to delaying execution, has already given examples, and here is no longer an example.

4.2, ToDictionary

4.3, the last, single

First: Select the primary element output from the output sequence

Last: Select the final element output from the output sequence

Single: A unique element that is used to return a unique element from an input sequence or satisfies a condition, where it is necessary to note that a single can only be used to return an element, and if there are multiple elements in the return sequence, the error will be

As shown in figure:

These three methods are used in the same way, only one first in here.

Example: Person defaulttest = pers. Where (p => p.sex = = "female"). A ();

Results:

4.3, sequenceequal: To determine whether two sequence is equal

Bool test=list. SequenceEqual (List1);

Returns true if two sequences are equal, or false for equality

4.4, any, all

Any: Used to determine whether all elements in the input sequence meet the specified criteria

All: Determine if the input sequence contains elements or elements that meet the criteria

The result of both methods is bool type, by judging whether the elements of the available sequence satisfy the condition

Example:

BOOL Anytest = pers. All (p => p.sex = = "Male");

if (anytest)

{

Console.WriteLine ("All the people are not all men");

}

Else

Console.WriteLine ("All Persons are Men");

Results:

The use of any is similar to the usage of all, and there is no example here.

4.5, Contains: Determine whether there are specified elements in the sequence, return a Boolean value

Example:

BOOL Anytest = pers. Select (P => p.name). Contains ("Olive");

if (!anytest)

{

Console.WriteLine ("Contains does not exist for the queried element.) ");

}

Else

Console.WriteLine ("contains exists the element being queried.) ");

Results:

This section is about here, mainly speaking of delayed implementation and not delayed implementation, I hope to be helpful to everyone, but also hope that we have a lot of criticism, common exploration and common progress. I'll focus on LINQ to XML in the next section.

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.