【问题标题】:Linq select many into new columnLinq选择许多进入新列
【发布时间】:2015-04-08 23:40:11
【问题描述】:

我正在尝试使 jquery 自动完成,其中我使用标签和值 like in this post,这意味着我需要我的 json 格式为

{ label: 'label text', value: 'value text' }

但是我正在过滤一个员工列表,它是一个具有以下结构的类:

public sealed class Employee
{
    public string Name { get; set; }
    public string PersonnelNumber { get; set; }
    public int RecID { get; set; }
    public string Email { get; set; }
}

所以我尝试了以下Linq来获取标签的格式,我需要的值:

var jsonResult = employees
                  .SelectMany(emp => new { label = emp.Name, value = emp.RecID })
                  .ToList();

employees 是 Employee 对象的列表,但它引发了构建错误

错误 1 ​​无法从用法中推断方法“System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable, System.Func>)”的类型参数。尝试明确指定类型参数。

如何解决此问题以在新的对象列表中获取 NameRecID,并将 labelvalue 作为其输出?

【问题讨论】:

  • 如果你要回家 - 那我也是! :D

标签: c# linq


【解决方案1】:

我想你只想在这里使用Select

var jsonResult = employees
    .Select(emp => new { label = emp.Name, value = emp.RecID })
    .ToList();

【讨论】:

  • 谢谢,这就是我想要的。复活节长周末过后,我的大脑没有恢复速度,我认为SelectMany 是为你想要多张唱片而准备的!
【解决方案2】:

SelectMany 用于“展平”一组集合。由于您只有一个集合,请使用Select

var jsonResult = employees.Select(emp => new { label = emp.Name, value = emp.RecID })
                          .ToList();

【讨论】:

    猜你喜欢
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多