【问题标题】:Having issue with select statement [closed]选择语句有问题[关闭]
【发布时间】:2013-07-19 11:32:42
【问题描述】:

我有这个方法

public CreateModule GetModuleDetails(long id)
{
    var module = (_dbSis.Modules.Where(t => t.Id == id).Select(m => new CreateModule
    {
        Id = id,
        ModuleId = m.ModuleId,
        TypeName = m.ModuleType.TypeName,
        KindName = m.ModuleType.ModuleKind.KindName,
        Properties = m.PropertyConfiguration.PropertyInstances.Select(
            x => new Property { Name = x.Property.Name, Value = x.Value })
    }));

    return (module.FirstOrDefault());
}

在此方法中,假设 Id 40 的模块具有两个属性名称和两个属性值。我想要一个只返回其中两个属性名称和值的函数,所以基本上是上面函数中的 Properties 字段,它是 IEnumerable 类型的。我做了这个,现在不行

 public List<Property> GetModuleProperties(long id)
 {
     var moduleProperties = _dbSis.Modules.Where(m => m.Id == id).SelectMany(p => new Property()
     {
         Name = p.PropertyConfiguration.PropertyInstances.Select(z=>z.Property.Name),
         Value = p.PropertyConfiguration.PropertyInstances.Select(x=>x.Value)
     });
      return (moduleProperties);
  }

但是我使用 Linq 分配 NameValue 的行显示错误,因为 linq 表达式返回 Name 字段的两个名称和 Value 字段的两个值。

我该如何解决这个问题,以便该方法返回正确的值列表?

实际上,现在这个模块有两个属性名称:Physical ID 和 FirmwareVersion 和两个值:123456 和 1.02。

【问题讨论】:

  • “不能正常工作”是什么意思?它“显示错误”?错误信息是什么?

标签: c# linq list select ienumerable


【解决方案1】:

看起来像你想要的:

return _dbSis.Modules.Where(t => t.Id == id)
    .SelectMany(m => m.PropertyConfiguration.PropertyInstances)
    .Select(i => new Property { Name = i.Property.Name, Value = i.Value })
    .ToList();

或者:

return _dbSis.Modules.Where(t => t.Id == id)
    .SelectMany(m => m.PropertyConfiguration.PropertyInstances.Select(i => new Property {
        Name = i.Property.Name,
        Value = i.Value
    })
    .ToList();

【讨论】:

  • 是的。我尝试了许多选择,但最终没有列出。这解决了问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-23
  • 1970-01-01
  • 2021-04-10
相关资源
最近更新 更多