2014-02-25 139 views
0

採取以下程序:序列化對象數組屬性值

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 }

是否有可能從WriteLine內部解析此

這是我最近遇到的一個更大問題的簡化,我需要從WriteLine內部解決這個問題,因爲我在查詢中執行了這個「序列化」我不能執行一個以上的陳述。

+0

只是刪除新 – user2525463

回答

3

而不是選擇匿名使用類型:

records.Select(r => r.FirstName + " " + r.LastName) 

所以你Console.WriteLine可能是:

Console.WriteLine(string.Join(", ", records.Select(r => r.FirstName + " " + r.LastName))); 
+0

或'.Aggregate()' – Magus

+0

哇,這是快速和簡單。謝謝。我很抱歉問這麼簡單的問題! – Raptor

+0

@JosuéMolina,不用擔心這個問題很簡單,現在有很多選擇:) – Habib

2

試試這個,

Console.WriteLine(string.Join(", ", records.Select(r => String.Format("{0} {1}", r.FirstName, r.LastName))); 
+0

由於需要進行替換,因此'string.Format'效率低於簡單的級聯。它肯定會起作用,但在很多情況下應該避免。 – Magus

1

你現在重新創建一個動態對象。我覺得你的意思是這樣的:

Console.WriteLine(string.Join(", ", records.Select(r => r.FirstName + " " + r.LastName))); 
1

只需使用內嵌的lambda表達式如下:

Console.WriteLine(string.Join(", ", records.Select(r => r.FirstName + " " + r.LastName)); 
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())));