如何从Linq查询中提取结果? [英] How to extract results from a Linq query?

查看:170
本文介绍了如何从Linq查询中提取结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Program
{
    static void Main(string[] args)
    {
        MyDatabaseEntities entities = new MyDatabaseEntities();

        var result = from c in entities.Categories
                        join p in entities.Products on c.ID equals p.IDCategory
                        group p by c.Name into g
                        select new
                        {
                            Name = g.Key,
                            Count = g.Count()
                        };

        Console.WriteLine(result.ToString());
        Console.ReadLine();
    }
}

如何从结果集中提取值,以便可以使用它们?

How can I extract the values from ths result set so I can work with them?

推荐答案

foreach (var item in result)
{
    var name = item.Name;
    var count = item.Count;
    ...
}

这仅适用于LINQ查询所在的方法,因为编译器仅会知道LINQ select中使用的匿名对象类型(new { })中的可用属性.

This will only work inside the same method where the LINQ query is located, since the compiler will only then know which properties are available in the anonymous object type (new { }) used in your LINQ select.

如果您将LINQ查询返回给调用方法,并且希望以上述方式访问它,则必须定义一个显式类型并在LINQ查询中使用它:

If you return a LINQ query to a calling method, and you want to access it in the way shown above, you'd have to define an explicit type and use it in your LINQ query:

class NameCountType
{
    public string Name { get; set; }
    public int Count { get; set; }
}

...

return from ... in ...
       ...
       select new NameCountType
              {
                  Name = ...,
                  Count = ...,
              };

这篇关于如何从Linq查询中提取结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆