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", "Johns开发者_运维百科on"),
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.
精彩评论