【问题标题】:Select a table column from IEnumerable using Linq使用 Linq 从 IEnumerable 中选择一个表列
【发布时间】:2017-10-16 21:38:06
【问题描述】:

通过使用 Sqlite,我的表格如下:

public class Medication
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
    public string unique_id { get; set; }
    public string username { get; set; }
    public string insulin_type { get; set; }
    public string units { get; set; }
    public string status { get; set; }

    public string alarm_time { get; set; }
    public Medication() { }
}

现在我想使用IEnumerable 获取一个列alarm_time 列表,但我不知道如何获取它。下面是我的代码:

public IEnumerable<Medication> AllMedicationResults()
{
    return (from t in _connection.Table<Medication>()
            select t).ToList();
}

如何在上面的代码中包含alarm_time 列。

【问题讨论】:

  • 您只需要alarm_time 列吗?
  • 是的@GiladGreen

标签: c# linq sqlite


【解决方案1】:

在您的 select 请求中仅请求该属性(并更改方法返回类型)

public IEnumerable<string> AllMedicationResults()
{
    return (from t in _connection.Table<Medication>()
            select t.alarm_time).ToList();
}

但是 IMO 只使用方法语法会看起来更简洁:

public IEnumerable<string> AllMedicationResults()
{
    return  _connection.Table<Medication>().Select(t => t.alarm_time).ToList();
}

请注意,当您返回 IEnumerable&lt;T&gt; 时,您可能需要考虑删除 ToList() 并使用 linq 延迟执行的好处

【讨论】:

  • 非常感谢@Gilad
  • 8 分钟后给你打勾
  • 所以如果我删除 ToList() ,我将返回一个纯 IEnumerable 项目,这意味着如果我输入 ToList() ,他们会将其转换为列表?
  • @Idris Stack -yes
猜你喜欢
  • 2010-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-06
相关资源
最近更新 更多