C # Write SQL-like statements in List (that is, writing them to beginners)

Source: Internet
Author: User

This article is written to C # For Beginners. The veteran will not read it. It is actually about LINQ. Thank you for reminding me on the first floor.

In many cases, it is easy to pick out a list of elements from a relational table and use SQL statements. In fact, similar methods can also be used in the C # list, although the select (), where () and other statements are integrated in the list, the following methods are also feasible if your judgment rules are complex or you want to make it clear:

Assume that you have a class

public class People{    public string Name { get; set; }    public int Age { get; set; }}
And there are some initialization statements
List<People> PeopleList = new List<People>();PeopleList.Add(new People() { Name = "Haocheng Wu", Age = 24 });PeopleList.Add(new People() { Name = "Haocheng Wu", Age = 25 });PeopleList.Add(new People() { Name = "James Wu", Age = 23 });

You can use the following SQL statement-like method for select

List<string> SubPeopleNameList1 = (from people in PeopleList                              where people.Name == "Haocheng Wu" && people.Age == 24                              select people.Name).ToList<string>();
Of course, you can also use a row instead. 
List<string> SubPeopleNameList2 = PeopleList.Where(people => people.Name == "Haocheng Wu" && people.Age == 24).Select(people => people.Name).ToList();

However, it is clear that the first method is more clear, especially when the judgment conditions are quite complex.

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.