【问题标题】:Xamarin SQLite.net group columns by data and sum numbersXamarin SQLite.net 按数据和总和数字对列进行分组
【发布时间】:2020-07-14 10:19:15
【问题描述】:

我正在学习 Xamarin,我正在使用这个 [sqlite 插件][1.我想按日期(MyCreateDate)汇总表值,并将这些日期(moth,yeah)中的单词数(Word1)相加。

例如,如果我有:

3 words in November 2001, nothing  in December 2001, 6 words in january 2002,2 words in febuary 2002, nothing  in March 2002.

我希望得到类似的回报:

Moth      Year   NumberWords
11        2001      3 
12        2001      0
1         2002      6
2         2002      2
3         2002      0

这是我的模型 Model.cs:

[PrimaryKey, AutoIncrement]
public int ID { get; set; }

[JsonProperty(PropertyName = "id")]
public string MyId { get; set; }

[JsonProperty(PropertyName = "myCreated")]
public DateTime MyCreateDate { get; set; } = DateTime.UtcNow; // with this value of date

[JsonProperty(PropertyName = "myUpdate")]
public DateTime MyUpdateDate { get; set; } = DateTime.UtcNow;

[JsonProperty(PropertyName = "complete")]
public bool Complete { get; set; }

[JsonProperty(PropertyName = "wordissaved")]
public bool WordIsSaved { get; set; } = false;

[JsonProperty(PropertyName = "word1")]
public string Word1 { get; set; }

[JsonProperty(PropertyName = "word2")]
public string Word2 { get; set; }

这是数据库 MyWordsDatabase.cs,我已经设法获取单词并选择随机单词:

class MyWordsDatabase
    {
        private SQLiteAsyncConnection conn;

        //CREATE  
        public MyWordsDatabase()
        {
            conn = DependencyService.Get<ISQLite>().GetConnection();
            conn.CreateTableAsync<MyWords>();
        }

        //READ  
        public  Task <List<MyWords>> GetWords()
        {
            var wordList = conn.Table<MyWords>();
            return wordList.OrderByDescending(w => w.ID).ToListAsync();

        }

        // Select ramdon words and put them in a list 
         public   Task<List<MyWords>> GetRandomListWords(int number)
        {
            var words =  conn.QueryAsync<MyWords>("select DISTINCT  * from MyWords ORDER BY RANDOM() LIMIT " + number + "");

            return  words;
        }

     }

感谢您的帮助

【问题讨论】:

  • 为什么要使用字符串作为日期列?这让你想做的事情变得非常困难。
  • @Jason 你可以这样做,因为日期对我来说没问题
  • @Jason 我已经更新了代码

标签: c# sqlite xamarin.forms sqlite-net


【解决方案1】:

您可以使用 LINQ 进行分组

var query = (from w in wordList
         group w by new {w.MyCreateDate.Year, w.MyCreateDate.Month}
         into grp
                select new
                {
                    grp.Key.MyCreateDate.Year,
                    grp.Key.MyCreateDate.Month,
                    Quantity = grp.Count()
                }).ToList();

【讨论】:

  • 我在“grp.Key.MyCreateDate.Year”和“grp.Key.MyCreateDate.Month”行有一个错误:'' 确实不包含“MyCreateDate”的定义,并且无法找到接受“”类型的第一个参数的可访问扩展方法“MyCreateDate”(您是否缺少 using 指令或程序集引用?)
猜你喜欢
  • 2021-05-06
  • 1970-01-01
  • 2021-04-25
  • 2019-02-12
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
相关资源
最近更新 更多