使用Linq连接类的属性列表 [英] Using Linq to concatenate a list of property of classes

查看:76
本文介绍了使用Linq连接类的属性列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了这个问题(使用LINQ连接字符串)对于字符串,但是如果我想连接一个字符串列表,而该字符串是类的属性,会发生什么呢?

I've seen this question (Using LINQ to concatenate strings) which works for strings but what happens if I would like to concatenate a list of string where the string is the property of a class?

该问题中提出的方法不起作用(我已经尝试过).

The method proposed in that question doesn't work (I've tried).

给出一个数组或People,我想要一个包含其名称串联的字符串.

Given an array or People I want a string which contains the concatenation of their names.

x => person.Name

我该如何解决这个问题?

How can I solve this problem?

推荐答案

这将为您完成工作:

var res = yourList.Select(x => x.Name).Aggregate((current, next) => current + ", " + next);

但是,我建议您使用String.Join(string separator, IEnumerable<string> values):

var res = String.Join(", ", yourList.Select(x => x.Name));

其他详细信息:

Additional details:

要在这种情况下说实话,您可以使用AggregateString.Join().如果我们测试两个查询的执行时间,我们将看到第二个查询比第一个查询快.但是原因不是Aggregate()功能.问题是我们将字符串串联在一起.这会导致很多中间字符串,这会导致性能不佳.如果仍要使用Aggregate并提高性能,则可以使用StringBuilder.Append:

To tell the truth in such situations you can use either Aggregate or String.Join(). If we tests the execution times of the both query, we will see that the second is faster than the first one. But the reason is not Aggregate() function. The problem is we are concatenating strings in a loop. It will cause a lots of intermediate strings which will cause a bad performance. You can use StringBuilder.Append, if you want still to use Aggregate and increase the performance:

 var res = yourList.Select(x => x.Name)
                   .Aggregate(new StringBuilder(), (current, next) => current.Append(next).Append(", ")).ToString();

但是,String.Join()已经在内部使用了StringBuilder,因此,这将是最佳选择.

But, String.Join() uses a StringBuilder internally already and for that reason it will be the best choice.

这篇关于使用Linq连接类的属性列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆