The last time we talked about how to retrieve array content from linq. Since net2.0 and later, generics have become a common application technology.
For example, if the list type is supported, the example is as follows:
Class Program
{
Static void Main (string [] args)
{
List <Books> samplebooks = new List <Books> (){
New Books {Id = 1, Name = "book1 "},
New Books {Id = 2, Name = "book2 "},
New Books {Id = 3, Name = "book3 "}
};
Var book = samplebooks. Where (p => p. Name. Contains ("2 "))
. Select (p => p. Name );
Foreach (var item in book)
{
Console. WriteLine (item );
}
Console. Read ();
}
}
Class Books
{
Public int Id {get; set ;}
Public string Name {get; set ;}
}
The above example is just a common scenario. Does linq support us. net. In fact, linq supports all sets that implement the IEnumable <T> interface ,. most collections in. net implement this interface, but not all collections implement this interface. In fact, this interface is implemented only when strong-type Hu sets are supported, such as arrays, lists, and dictionaries, they are all strongly typed, so we can apply the linq to object technology to these objects.
For non-generic sets, such as arrarlist and dataset, the combination of equal sets does not implement the IEnumable <T> interface, but implements the IEnumabler interface. Isn't it possible to apply the generic technology, of course, there is still a way to deal with this, as we will mention later.
Next, let's take a look at some of the basic operations of linq:
Where operation:
Function: Conditional Filtering
Operator declaration:
Public static IEnumerable <T> where <T> {
This IEnumerable <T> source,
Func <T, bool> predicate
}
The first element of predicate indicates the element to be judged. If this element is judged, true is returned; otherwise, false is returned.
By observing the source, we can also find that the where is essentially an extension method, which is obviously exposed through the this keyword. The essence of the implementation of predicate is to delegate the processing, through the observation of the parameter predicate can also be clearly reflected.
At the same time, where also provides an overloaded version:
Public static IEnumerable <T> where <T> {
This IEnumerable <T> source,
Func <T, int, bool> predicate
}
The second parameter of predicate indicates the index position of the current element in the source sequence (starting with 0)
The following is an example code for this overload:
IEnumerable <Books> book = samplebooks. where (book, index) => (book. name. contains ("2") & (index & 1) = 1 ));
The above code is used to find a book whose name contains 2 odd numbers in the sequence.