简体   繁体   English

concat linq查询结果为字符串?

[英]Concat linq query result to string ?

I have this simple class : 我有这个简单的课程:

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

And I have a dictionary : 我有一本字典:

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"};

And here I see all the items in a visible way : 在这里,我以可见的方式看到所有项目:

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

output : 输出:

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

but I want it to be as a string ! 但我希望它成为字符串!

something like this string value : 像这样的字符串值:

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

I could do it with ToArray and string.join : 我可以用ToArray和string.join做到这一点:

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

But I'm sure there is a better ( shorter , elegant) way using this statement : (with a bit of addition) 但是我敢肯定,使用以下语句会有更好(更简短,更优雅)的方式:(还有一点补充)

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

Any help ? 有什么帮助吗?

You can use 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();

Or by using a StringBuilder 或使用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();

You solution is fine, the only thing I would get rid of is the call to ToArray , so 您的解决方案很好,我唯一要摆脱的就是对ToArray的调用,因此

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM