首页 > 解决方案 > 使用 Xamarin.Forms 从 Sqlite 数据库中获取数据

问题描述

当我使用 Xamarin 和 sqlite 创建应用程序时。我运行了一条语句,但它在模拟器屏幕中显示了这句话:System.Linq.Enumerable + SelectEnumerableIterator`2[AppUI.Entries, System.String]

这是我的条目类:

public class Entries
{
    public Entries()
    {

    }

    public Entries(string word)
    {
        this.word = word;
    }
    public Entries(string word, string wordtype, string definition)
    {
        this.word = word;
        this.type = wordtype;
        this.defn = definition;
    }   
    public string word
    { get; set; }

    public string type
    { get; set; }

    public string sdex { get; set; }
    public int wlen { get; set; }

    public string defn
    { get; set; }

这是 DatabaseManager 类。function GetDef() 是我推荐的语句。

public class DatabaseManager
{
    SQLiteConnection dbConnection;
    public DatabaseManager()
    {
        dbConnection = DependencyService.Get<ISQLite>().GetConnection();
    }


    public string GetDef(string w)
    {
        return dbConnection.Table<Entries>().Where(x => x.word == w).Select(x => x.defn).ToString();
    }


}

我不知道为什么会这样?请帮忙。太感谢了

标签: sqlitexamarinxamarin.formsxamarin.androidandroid-sqlite

解决方案


这部分查询和 Linq 返回一个IEnumerable(即零个或多个Entries对象)。

dbConnection.Table<Entries>().Where(x => x.word == w)

Linq 投影的这一部分假设它只有一个Entries对象:

.Select(x => x.defn).ToString();

因此,请使用从枚举中First获取第一条记录(或返回if no records exist ):nullFirstOrDefault

return dbConnection.Table<Entries>()
          .Where(x => x.word == w)
          .FirstOrDefault()?
          .defn;

推荐阅读