c# - 如何使用 LINQ 从列表中获取逗号分隔的值列表?

标签 c# linq

我有一个短语列表:List<Phrase>其中 Phrase 对象的属性为 PhraseId .我需要做的是获取一个字符串,该字符串由用单引号括起来的每个 Id 和后跟一个“,”组成,但最后一个 PhraseId 除外?

换句话说,我想要一个看起来像这样的字符串:

'id1','id2','id3'

我看过 LINQ Select 命令,但我认为这只是给了我另一个列表。

谁能建议我该怎么做?

最佳答案

这应该可行

var result = string.Join(",", phrases.Select(x => $"'{x.PhraseId}'"));

其他资源

String.Join Method

Concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member.

Enumerable.Select Method

Projects each element of a sequence into a new form.

$ - string interpolation (C# Reference)

The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolated expressions. When an interpolated string is resolved to a result string, items with interpolated expressions are replaced by the string representations of the expression results. This feature is available in C# 6 and later versions of the language.

关于c# - 如何使用 LINQ 从列表中获取逗号分隔的值列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52901498/

相关文章:

c# - 反序列化从 Azure 表检索的 DynamicTableEntity

c# - 大数字的 IsNumeric Helper 方法

c# - 一圈还是两圈? (如何阅读 IL)

c# - 字符串或二进制数据将在 Linq 中被截断

带有包含多个条件的 WHERE 子句的 LINQ 查询

c# - 如何让 WinForms 自定义控件的默认值在第一次放在窗体上时得到尊重

c# - ASP .Net 用户控件错误处理

c# - 这个流行的 StackOverflow 答案不正确吗?

c# - 在 C# 中通过 Web 服务传输图像的最佳方式是什么?

c# - 将两个属性联合到普通列表 c#