简体   繁体   中英

How to query this in LINQ? C#

Considering the following:

public class Person
{
    public Person(string fName, string lName)
    {
        this.firstName = fName;
        this.lastName = lName;
    }

    public string firstName;
    public string lastName;
}

class App
{
    static void Main()
    {
        Person[] peopleArray = new Person[3]
        {
            new Person("John", "Smith"),
            new Person("Jim", "Johnson"),
            new Person("Sue", "Rabon"),
        };
        // select lastName from peopleArray where firstName like '%'J'%'
    }
}

Using LINQ, how can express this:

select lastName from peopleArray where firstName like '%'J'%'

I want to print the lastnames of all person having "J" in their firstname . I find it hard to express it in LINQ. Help Please....

var query = from person in peopleArray 
            where person.firstName.Contains("J") 
            select person.lastName;

// or
var query = peopleArray.Where(p => p.firstName.Contains("J")).Select(p => p.lastName);

// use results, print to screen?
foreach (string lastName in query)
{
     Console.WriteLine(lastName);
}
List<string> matchingLastNames = (from person in peopleArray 
                                  where person.firstName.Contains("J") 
                                  select person.lastName).ToList<string>();

I give you some advices. 1.learn what delegate is. 2.learn what lambda expression is. 3.learn extend methods.

if you learn these. you can write anything you like in linq.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM