concat linq查询结果到字符串?

时间:2013-05-27 12:56:15

标签: c# .net linq

我有这个简单的课程:

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)

任何帮助?

2 个答案:

答案 0 :(得分:4)

您可以使用Aggregate Extension Method

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();

答案 1 :(得分:2)

你解决方案很好,我唯一能解决的就是调用ToArray,所以

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

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