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();
}
}
如何从结果集中提取值,以便我可以使用它们?
答案 0 :(得分:11)
foreach (var item in result)
{
var name = item.Name;
var count = item.Count;
...
}
这只能在LINQ查询所在的同一方法内部工作,因为编译器只会知道LINQ new { }
中使用的匿名对象类型(select
)中可用的属性。
如果将LINQ查询返回给调用方法,并且想要以上面显示的方式访问它,则必须定义显式类型并在LINQ查询中使用它:
class NameCountType
{
public string Name { get; set; }
public int Count { get; set; }
}
...
return from ... in ...
...
select new NameCountType
{
Name = ...,
Count = ...,
};
答案 1 :(得分:0)
例如:
foreach (var x in result)
{
Console.WriteLine(x.c.Name);
}
答案 2 :(得分:0)
var results = (from myRow in ds.Tables[0].AsEnumerable()
where myRow.Field<String>("UserName") == "XXX"
select myRow).Distinct();
foreach (DataRow dr in results)
UserList += " , "+dr[0].ToString();