使用LINQ计算BsonDocuments并将结果放入新列表中

时间:2016-11-28 21:06:36

标签: c# mongodb linq count

确定。我很难过,因为我不太了解LINQ,但这是问题所在。我有一个BsonDocuments列表,其结构如下:

{ "Produce" : "apple", "CompanyName" : "Ralphs", "Link" : "www.ralphs.com" },
{ "Produce" : "apple", "CompanyName" : "Ralphs", "Link" : "www.ralphs.com" },
{ "Produce" : "apple", "CompanyName" : "Albertsons", "Link" : "www.albertsons.com" },
{ "Produce" : "banana", "CompanyName" : "Ralphs", "Link" : "www.ralphs.com" }

如何使用LINQ查询此列表以查找特定的计数匹配,并将所有数据作为唯一键放在新的BsonDocuments列表中?例如,如果我要对上面的项目进行分组,我会得到:

{ "Produce" : "apple", "CompanyName" : "Ralphs", "Link" : "www.ralphs.com" }, // Count = 2
{ "Produce" : "apple", "CompanyName" : "Albertsons", "Link" : "www.albertsons.com" }, // Count = 1
{ "Produce" : "banana", "CompanyName" : "Ralphs", "Link" : "www.ralphs.com" } // Count = 1

但由于我只想要一个特定的计数(例如2),我的最终列表应该只包含

{ "Produce" : "apple", "CompanyName" : "Ralphs", "Link" : "www.ralphs.com" }, // Count = 2

我已经知道如何使用针对MongoDB数据库的聚合框架来实现这一点,但是如果可能的话,我想知道如何使用LINQ在内存中执行此操作。非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

试试这段代码:

    class Class1
    {
        public string Produce { get; set; }
        public string CompanyName { get; set; }
        public string Link { get; set; }
    }

    private void button3_Click(object sender, EventArgs e)
    {
        List<Class1> lst = new List<Class1>();
        lst.Add(new Class1() { Produce = "a", CompanyName="b", Link="c" });
        lst.Add(new Class1() { Produce = "a", CompanyName = "b", Link = "c" });
        lst.Add(new Class1() { Produce = "a", CompanyName = "d", Link = "c" });
        lst.Add(new Class1() { Produce = "e", CompanyName = "b", Link = "c" });

        var result = lst.GroupBy(x => x.Produce + x.CompanyName + x.Link).Select(g => new { Produce = g.First().Produce,
            Company = g.First().CompanyName,
            Link = g.First().Link,
            Count = g.Count()
        }).ToList();

    }