使用LINQ中的iEnumerable选择一个表列[英] Select a table column from IEnumerable using Linq

本文是小编为大家收集整理的关于使用LINQ中的iEnumerable选择一个表列的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

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包括在上面的代码中.

推荐答案

在您的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<T>时,您可能需要考虑删除ToList()并使用LINQ的部门执行的好处

本文地址:https://www.itbaoku.cn/post/1556978.html

问题描述

Am having my table as below , by the usage of 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() { }
}

Now I want to use IEnumerable to get a Column alarm_time List but I don't know how to get it. Below is my code for that:

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

How can I include the Column alarm_time in that code above.

推荐答案

In your select request only that property (and change method return type)

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

But IMO it will look cleaner to just use method syntax:

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

Notice that as you are returning an IEnumerable<T> you might want to consider removing the ToList() and using the benefits of linq's deffered execution