如何运行查询以系统地将结果添加到表或列表中?

时间:2015-07-03 00:02:53

标签: c# asp.net linq

基本上,这就是我想要做的。

如果数据集是这样的:

|----------------------------------------------|
|ShopName      |Fruit                          |
|----------------------------------------------|
|Kens Shop     |Eggplant                       |
|Kens Shop     |Potato                         |
|Kens Shop     |Asparagus                      |
|Bens Shop     |Eggplant                       |
|Bens Shop     |Carrot                         |
|Sarahs Shop   |Potato                         |
|Sarahs Shop   |Asparagus                      |
------------------------------------------------

我想要的结果是:

----------------------------------
|Vegetable   |Count              |
|---------------------------------
|Eggplant    |2                  |
|Potato      |2                  |
|Asparagus   |2                  |
|Carrot      |1                  |
----------------------------------

对于这个特殊的例子,我并不关心这家商店有多少蔬菜。

理想情况下,我想将“商店名称”放入多行文本框并通过C#ASP.NET前端进行迭代,然后将其全部绑定到GridView进行查看。 / p>

 For Each strLine As String In TextBox1.Text.Split(vbNewLine)
            ' somehow add the results of this "shop" to an existing table or list, and add the results to what is already there
        Next

如果我可以使用Linq to SQL以某种方式做到这一点,那将会更加出色。

那么...... Linq to SQL逻辑会发生什么样的事情呢?或者如果不可能,可以在基本的SQL查询中完成吗?

谢谢:)

1 个答案:

答案 0 :(得分:1)

SQL语法

SELECT Fruit AS Vegetable, Count(*) AS [Count] 
    FROM Shops 
    GROUP BY Fruit

Linq语法(伪代码 - 可以优化)。首先创建两个帮助struct来处理输入和分组输出。

struct Shop
{
    public string ShopName { get; set; }
    public string Fruit { get; set; }
}
struct GrouppedFruit
{
    public string Vegetable { get; set; }
    public int Count { get; set; }
}

现在查询DataBase以返回SELECT查询并将其插入List

DataTable table = manager.GetData("SELECT * FROM Shops");
var shops = new List<Shop>();
foreach (DataRow row in table.Rows)
{
    shops.Add(new Shop
    {
        ShopName = row["ShopName"].ToString(),
        Fruit = row["Fruit"].ToString()
    });
}

使用LINQ

分组输出
//query syntax
var grouppedFruits = (from shop in shops
                        group shop by shop.Fruit into grouping
                        select new GrouppedFruit
                        {
                            Vegetable = grouping.Key,
                            Count = grouping.Count()
                        }).ToList();
//method syntax
var grouppedFruits1 = shops
    .GroupBy(shop => shop.Fruit)
    .Select(g => new GrouppedFruit 
    { 
        Vegetable = g.Key, 
        Count = g.Count() 
    }).ToList();