How to do this in LINQ?
I can't express what I want to do. Please help. Considering my code below开发者_JS百科:
void Main()
{
List<Person> person = new List<Person>
{
new Person { Name = "Maria Anders", Age = 21 },
new Person { Name = "Ana Trujillo", Age = 55 },
new Person { Name = "Thomas Hardy", Age = 40 },
new Person { Name = "Laurence Lebihan", Age = 18 },
new Person { Name = "Victoria Ashworth", Age = 16 },
new Person { Name = "Ann Devon", Age = 12 }
};
person.Select(x => new { x.Name, x.Age }).Dump();
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
I want to print the Name | Age | Status
of a person.
Status
is a derived column. Where it should have a value of either "Adult
" if the person's age is >= 18, otherwise "Under age".
First you need to add a property named Status
to class Person
.
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Status
{
get { return Age >= 18 ? "Adult" : "Under age"; }
}
public override string ToString()
{
return string.Format("{0}|{1}|{2}",Name,Age,Status);
}
}
then you can loop into the list of person to do your action:
foreach(Person p in persons)
{
Console.WriteLine(p);
}
//Or
persons.ForEach( p => Console.WriteLine(p) );
The reason of adding Status
property and overriding ToString
method is to put the logic in one place. Otherwise, suppose some day, you need to change "Under age" to "Nonage", you won't need to change the strings everywhere but only one place in your Person
class.
How about:
person.Select(p =>
String.Format("{0} | {1} | {2}",
p.Name, p.Age, p.Age >= 18 ? "Adult" : "Under age"))
.Dump();
Then somewhere else:
static void Dump(this IEnumerable<string> ss)
{
foreach(var s in ss)
{
Console.WriteLine(s);
}
}
var y = person.Select(x => new { x.Name, x.Age, Status = x.Age > 18 ? "Adult" : "Minor" });
Its simple.. sb.ToString() will give you what you want.
StringBuilder sb = new StringBuilder();
foreach(Person p in person)
{
string status = p.Age >= 18 ? "Adult" : "Not Adult";
sb.AppendLine(String.Format("{0} {1} {2}",p.Name,p.Age.ToString(),status));
sb.AppendLine(Environment.NewLine);
}
person.Select(x => new { x.Name, x.Age ,Status = (x.Age>=18) ? "Adult":"Under Age"})
try:
person.Select(x => new {Name = x.Name, Age = x.Age, Status = ((x.Age>=18) ? "Adult" :"Child") }); ;
精彩评论