How to Convert a list of objects to a string list
I have a list of Person objects
class Person
{
string FirstName{get;set;}
int Age {get;set;}
}
Now in this Person objects list
Person1 has FirstName="Alan", Age=20
Person 2 has FirstName="Josephine", Age=21
I need to get a new List, where each list item has the first name concatenated with the age
List I need:
Alan:20
Josephine:21
...so on
I have this so far...
var PersonConcatenatedList= from p in PersonList
select new {firstName= p.FirstName, Age=p.Age};
err...but now how to ouput the desired list format ? :(
Any help will be greatly appreciated. thanks
Use string.Join
:
var PersonConcatenatedList = PersonList
.Select(x => string.Join(":", x.FirstName, x.Age));
Since you need a list of strings you shouldn't create ananymous types.Simple string concatanation would also work:
PersonList.Select(x => x.FirstName + ":" + x.Age));
If you want output as a single string, then use string.Join
via Environment.NewLine
and concatanate the results with new line character:
var output = string.Join(Environment.NewLine, PersonConcatenatedList);
String.Join()
is one way to go. But for good programming I suggest implementing the .ToString()
method.
class Person
{
string FirstName { get; set; }
int Age { get; set; }
public override string ToString()
{
return this.FirstName + ":" + this.Age;
}
}
Then simply use the following:
var result = personList.Select(person => person.ToString());
链接地址: http://www.djcxy.com/p/51378.html
上一篇: 映射列表与单独对象相比,Automapper行为有所不同
下一篇: 如何将对象列表转换为字符串列表