簡體   English   中英

concat linq查詢結果為字符串?

[英]Concat linq query result to string ?

我有這個簡單的課程:

class A
{
  public string Name { get; set; }
  public int Age { get; set; }
}

我有一本字典:

Dictionary<string,A> dic = new Dictionary<string,A>();

dic["a"]=new A(){ Age=2, Name="aa"};
dic["b"]=new A(){ Age=3, Name="baa"};
dic["c"]=new A(){ Age=4, Name="caa"};

在這里,我以可見的方式看到所有項目:

Console.WriteLine (dic.Select(f=>f.Key+" =>"+f.Value.Age+" "+f.Value.Name));

輸出:

a  =>2      aa  
b  =>3      baa  
c  =>4      caa 

但我希望它成為字符串!

像這樣的字符串值:

@"a  =>2      aa  \n
  b  =>3      baa  \n
  c  =>4      caa ";

我可以用ToArray和string.join做到這一點:

var t=dic.Select(f=>f.Key+"  =>"+f.Value.Age+"      "+f.Value.Name);
Console.WriteLine (String.Join("\n",t.ToArray() ));

但是我敢肯定,使用以下語句會有更好(更簡短,更優雅)的方式:(還有一點補充)

dic.Select(f=>f.Key+" =>"+f.Value.Age+" "+f.Value.Name)

有什么幫助嗎?

您可以使用匯總擴展方法

string s = dic.Aggregate(String.Empty, 
                         (current, f) => 
                         String.Format("{0}\n{1} => {2} {3}", 
                                       current, 
                                       f.Key, 
                                       f.Value.Age,
                                       f.Value.Name))
              .TrimStart();

或使用StringBuilder

string s = dic.Aggregate(new StringBuilder(), 
                         (current, f) => 
                         current.AppendLine(
                             String.Format("{0} => {1} {2}", 
                                 f.Key, 
                                 f.Value.Age,
                                 f.Value.Name))
              .ToString();

您的解決方案很好,我唯一要擺脫的就是對ToArray的調用,因此

Console.WriteLine (String.Join("\n",t ));

要么

Console.WriteLine (String.Join(Environment.NewLine, t));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM