[英]LINQ with group by for nested list
如果我的主要对象使用带有嵌套列表的Linq,则尝试过滤并获取列表。 我需要的是List<Category>
class Category contains List<Order> and List<Price>
但是我得到的结果被两个子对象分组,因此我没有得到确切的结果。 我想单独分组以得到结果。 以下是我的Linq查询,
我在这里做错了什么?
var resultList = (
from category in Connection.Table<Category>().ToList()
join order in Connection.Table<Order>().ToList()
on category.Id equals order.CategoryId
join price in Connection.Table<Price>().ToList()
on category.Id equals price.CategoryId
where category.Id == TestID
select new {
category.ID,
category.Name,
order,
price
} into grou
group grou by new {
grou.Id
} into grp
select new Category {
Id = grp.Id,
Order = grp.Select(x => x.order).ToList(),
Price = grp.Select(x => x.price).ToList()
}).ToList();
尝试以下类似的方法。 至少有一种情况您使用ID而不是ID:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
}
}
public class cConnection
{
public cConnection Connection { get; set; }
public List<cTable<Entity>> Table<Entiry>() { return null; }
public void Test()
{
int TestID = 123;
var resultList = (from mainObjectEntity in Connection.Table<MainObjectEntity>().ToList()
join child1Entity in Connection.Table<Child1Entity>().ToList()
on mainObjectEntity.Id equals child1Entity.MainObjectEntityId
join child2Entity in Connection.Table<Child2Entity>().ToList()
on mainObjectEntity.Id equals child2Entity.MainObjectEntityId
where mainObjectEntity.TestId == TestID
select new
{
id = mainObjectEntity.TestId,
mainObjectEntity = mainObjectEntity,
child1 = child1Entity,
child2 = child2Entity
})
.GroupBy(x => x.id)
.Select(grp => new {
TestID = grp.FirstOrDefault().id,
Child1Entity = grp.Select(x => x.child1).ToList(),
Child2Entity = grp.Select(x => x.child2).ToList()
}).ToList();
}
}
public class cTable<T> : Entity
{
public int MainObjectEntityId { get; set; }
public int TestId { get; set; }
}
public class Entity
{
public int Id { get; set; }
}
public class Child1Entity : Entity
{
}
public class Child2Entity : Entity
{
}
public class MainObjectEntity : Entity
{
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.