如何在LINQ中查询? C#

时间:2010-11-05 01:38:34

标签: c# linq

考虑以下因素:

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'%'
    }
}

使用LINQ,如何表达:

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

我想打印lastnames“J”的所有人的firstname。 我发现很难在LINQ中表达它。请帮助....

3 个答案:

答案 0 :(得分:9)

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);
}

答案 1 :(得分:1)

List<string> matchingLastNames = (from person in peopleArray 
                                  where person.firstName.Contains("J") 
                                  select person.lastName).ToList<string>();

答案 2 :(得分:-2)

我给你一些建议。 1.了解代表是什么。 2.了解lambda表达式是什么。 3.学习扩展方法。

如果你了解这些。你可以在linq中写下你喜欢的任何东西。