c# - LINQ 选择格式化值作为列表

标签 c# linq

我正在尝试获取列值并将其转换为格式化字符串值列表,我尝试了以下代码

List<string> _names = (from p in context.RakHolders select 
    string.Format("{0},{1}",  p.Name.Split(',')[0].Trim(), p.Name.Split(',')[1].Trim()))
    .ToList();

我的目的是获取名称列表,名称列中逗号之间没有不需要的空格

我在执行此行时遇到异常

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: LINQ to Entities does not recognize the method
'System.String Format(System.String, System.Object, System.Object)' method, and this method cannot be translated into a store expression.

如何使用 LINQ 完成这项工作[获取格式化列值的列表]

最佳答案

List<string> _names = (from p in context.RakHolders select p.Name)
    .ToList()
    .Select(name => name.Split(','))
    .Select(nameSplitted => string.Format("{0},{1}",  nameSplitted[0].Trim(), nameSplitted[1].Trim() ))
    .ToList();

说明:“string.Format”无法转换为 SQL,因此首先我们需要使用第一个“ToList()”具体化列表(这里我们获取名称列表,它比具体化完整实体高效得多)。将列表存储在内存中,您可以将其转换为您需要的形式。

关于c# - LINQ 选择格式化值作为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40417956/

相关文章:

C# decimal.Parse 行为

c# - 对于以 '{' 开头的名称,为什么 XName.Get 抛出 ArgumentException 而不是 XmlException ?

c# - Xbox360 上的 XNA 和 Linq

c# - linq to sql左连接,需要检查右表是否为空

c# - 项目包含多个 EDMX 文件时抛出 "the entity type is not part of the model for the current context"错误

c# 如何将日期时间转换为 4 个字节的字节数组

c# - 如何使用 SpecFlow 设置个人跟踪/日志记录

c# - 如何选择另一个列表中包含的不同元素列表?

c# - 在 Entity Framework 上运行原始 SQL 查询的 KeyValuePair

c# - 使用 C# 和 Linq 以 1000 组为一组处理文档的 46,000 行