gpt4 book ai didi

c# - 如何从 Linq 查询中提取结果?

转载 作者:太空狗 更新时间:2023-10-30 00:17:07 25 4
gpt4 key购买 nike

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();
}
}

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

最佳答案

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

这只会在 LINQ 查询所在的同一方法内起作用,因为编译器只会知道哪些属性在您的 LINQ 中使用的匿名对象类型 (new { }) 中可用选择

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

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

...

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

关于c# - 如何从 Linq 查询中提取结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3601301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com