It takes some time to learn about Linq. At the beginning, I am not very used to it. The more I use it, the more convenient I find it. Recently I read and used Lambda expressions for a while and found that this is indeed a good thing.
When we generate an IQueryable <T> object through a Linq query or other method, for example, we query the product list from the product table.
IQueryable<Product> product = from p in db.Products select p;
If we want to retrieve an item with ProductID 5 from the product list, we can use for or foreach for traversal and comparison, or write another Linq statement for query, all these methods can obtain the specified ProductID Product.
For Method
Product proOne; for (int i = 0; i < product.Count(); i++)
{
if (product.ToList().ElementAt(i).ProductID== 5)
{
proOne = product.ToList().ElementAt(i);
}
}
The foreach method is similar to the for method,
Linq query:
proOne = (from p in product where p.ProductID== 5 select p).ToList().ElementAt(0);
The above method is not a little troublesome and erased the advantages of the slow query of the Linq, so let's take a look at the Lambda expression method:
proOne = product.Single(p => p.ProductID== 5);
It takes only a few words to complete the tedious steps in the above several methods, and retains the advantages of the Linq delayed query. Is it nice to write a program like this?
After understanding the advantages of Lambda expressions, let's take a look at other usage of Lambda expressions and introduce the two most commonly used methods: Where and Select.
The first is the Select method:
var proIDList = product.Select(p => p.ProductID > 5);
We can find that the Select method is similar to the statement in the Single method. In fact, they return different objects. The Single method is to retrieve an object from the list. The Select method is used to retrieve the list of values of a field of multiple objects that meet the conditions in the list.
In this statement, the Select method returns an IEnumerable <int> object, while the Single method returns a Product object. The following Where method returns an IEnumerable <Product> Object List:
var proList = product.Where(p => p.ProductID > 5);
Where generates a column of Product objects, which must be different from the Select method.
This is something I have learned. I hope to share it with you. If you have any questions, please give me some comments.