采取以下计划:
using System;
using System.Collections.Generic;
using System.Linq;
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
var records = new Person[]
{
new Person{ FirstName = "John", LastName = "Doe", Age = 32 },
new Person{ FirstName = "Jane", LastName = "Doe", Age = 27 },
new Person{ FirstName = "Joe", LastName = "College", Age = 28 }
};
Console.WriteLine(string.Join(", ", records.Select(r => new
{
FullName = r.FirstName + " " + r.LastName
})));
}
}
预期输出是:
John Doe, Jane Doe, Joe College
但实际输出是:
{ FullName = John Doe }, { FullName = Jane Doe }, { FullName = Joe College }
是否可以从<{1}}内部解析 ?
这是我最近遇到的一个更大问题的简化,我需要在WriteLine
内解决这个问题,因为我在查询中执行此“序列化”;我不能执行多个语句。
答案 0 :(得分:3)
而不是选择匿名类型:
records.Select(r => r.FirstName + " " + r.LastName)
所以你的Console.WriteLine
可能是:
Console.WriteLine(string.Join(", ", records.Select(r => r.FirstName + " " + r.LastName)));
答案 1 :(得分:2)
试试这个,
Console.WriteLine(string.Join(", ", records.Select(r => String.Format("{0} {1}", r.FirstName, r.LastName) ));
答案 2 :(得分:1)
您正在重新创建动态对象。我认为你的意思是这样的:
Console.WriteLine(string.Join(", ", records.Select(r => r.FirstName + " " + r.LastName)));
答案 3 :(得分:1)
使用内联lambda表达式如下:
Console.WriteLine(string.Join(", ", records.Select(r => r.FirstName + " " + r.LastName));
答案 4 :(得分:1)
我建议使用ToString()方法。这使得方法更加清洁。
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public override string ToString() {
return string.Format("{0} {1}", FirstName, LastName);
}
}
然后
Console.WriteLine(string.Join(", ", records.Select(r => r.ToString())));