有没有办法在LinqToSql中按查询编写一个组而不是标量值?

时间:2008-10-10 08:04:54

标签: c# linq linq-to-sql

我的存储库中有这些地图。

public IQueryable<AwType> GetAwTypes()
{
    return from awt in _db.AwTypes
           select new AwType
           {
               Id = awt.Id,
               Header = awt.Header,
               Description = awt.Description
           };
}

public IQueryable<Aw> GetAws()
{
    return from aw in _db.Aws
           select new Aw
           {
               Id = aw.Id,
               Bw = (from bw in GetBws()
                          where bw.Id == aw.Bw
                             select bw
                         ).SingleOrDefault(),
               AwType = (from awt in GetAwTypes()
                            where awt.Id == awAwType
                            select awt
                        ).SingleOrDefault(),
               AwAttribute = aw.AwAttribute
           };
}

在服务中我希望将按AwType分组的Bws计为List<KeyValuePair<AwType, int>>。 当我调用linq查询时:

var awGroups = from aw in _repository.GetAws()
group aw by aw.AwType into newGroup
select newGroup;

List<KeyValuePair<AwType, int>> RetGroups = new List<KeyValuePair<AwType, int>>();
foreach (var group in awGroups)
{
    RetGroups.Add(new KeyValuePair<AwType, int>(group.Key, group.Count()));
}
return RetGroups;

我收到一个错误,说我不能分组一个对象,我必须通过像aw.AwType.Id这样的标量值进行分组。

有没有办法在一次通话中获得“AwType,int”对?

3 个答案:

答案 0 :(得分:1)

AwType是一种引用类型。对该引用类型进行分组是个坏主意......该查询中的每个AwType都是唯一引用,因此n个元素将产生n个组。

试试这个:

var awGroups = from aw in _repository.GetAws()
group aw by aw.AwType.ID into newGroup  //changed to group on ID
select newGroup;

List<KeyValuePair<AwType, int>> RetGroups = new List<KeyValuePair<AwType, int>>();
foreach (var group in awGroups)
{
    //changed to get the first element of the group and examine its AwType
    RetGroups.Add(new KeyValuePair<AwType, int>(group.First().AwType, group.Count()));
}
return RetGroups;

答案 1 :(得分:0)

您可以按匿名类型分组,例如new {Foo,Bar}

答案 2 :(得分:0)

根据我对linq的理解,您将尝试按表格的每一列进行分组。这只能通过列出组语句中表中的每个字段来完成,因此在您的情况下,您需要执行以下操作(我对Linq不是很了解)

var awGroups = from aw in _repository.GetAws()
group aw by aw.AwType.Id, aw.AwType.Header, aw.AwType.Description into newGroup
select newGroup;

或者如果这是您需要的唯一列,您可以按ID分组。

var awGroups = from aw in _repository.GetAws()
group aw by aw.AwType.Id into newGroup
select newGroup;