虽然我在MSDN和很多书中搜索过,但我找不到任何有关此类查询的帮助。也许这里有人能够帮助我。这是一个例子:
var query = from document in Database.Documents
group document.OwnerID by
new
{
OwnerName= document.Owner.OwnerName,
ReleaseDate= document.ReleaseDate,
OwnerID= document.OwnerID,
Status= document.StatusId
}
into grupo
select new AmountOfDocuments
{
OwnerName= grupo.Key.OwnerName,
ReleaseDate= grupo.Key.ReleaseDate,
OwnerID= grupo.Key.OwnerID,
UDocuments= grupo.Count(),
SDocuments= grupo.Count()
};
我需要让UDocuments和SDocuments分别返回状态等于U或S的文档数。我将不胜感激,但我需要弄清楚该查询本身的工作原理。
提前致谢!
答案 0 :(得分:1)
Lambda表达式是你的朋友!
UDocuments = grupo.Where(x => x.Status == "U").Count(),
SDocuments = grupo.Where(x => x.Status == "S").Count()
编辑:没有必要在哪里。
UDocuments = grupo.Count(x => x.Status == "U"),
SDocuments = grupo.Count(x => x.Status == "S")
答案 1 :(得分:1)
检查在Linqpad中创建的以下代码,它以两种不同的方式完成工作并产生相同的结果。第二个是优选的,因为它将Status作为值Grouping
投影,因此计数变得更简单
void Main()
{
var testList = Test.Create();
var result =
testList.GroupBy(x=>new {
x.OwnerName,
x.OwnerId,
x.ReleaseDates
})
.Select(y=>new {
y.Key.OwnerName,
y.Key.OwnerId,
statusU = y.Count(m=>m.status == "U"),
statusS = y.Count(m=>m.status == "S"),
});
result.Dump();
var result1 =
testList.GroupBy(x=>new {
x.OwnerName,
x.OwnerId,
x.ReleaseDates
},x=>x.status)
.Select(y=>new {
y.Key.OwnerName,
y.Key.OwnerId,
statusU = y.Count(m=>m=="U"),
statusS = y.Count(m=>m=="S"),
});
result1.Dump();
}
public class Test
{
public string OwnerName {get; set;}
public int OwnerId {get; set;}
public string status {get; set;}
public DateTime ReleaseDates{get; set;}
public static List<Test> Create()
{
return new List<Test>()
{
new Test
{
OwnerName = "ABCD",
OwnerId = 1,
status = "S",
ReleaseDates = DateTime.Now
},
new Test
{
OwnerName = "ABCD",
OwnerId = 1,
status = "S",
ReleaseDates = DateTime.Now
},
new Test
{
OwnerName = "ABCD",
OwnerId = 1,
status = "S",
ReleaseDates = DateTime.Now
},
new Test
{
OwnerName = "ABCD",
OwnerId = 1,
status = "U",
ReleaseDates = DateTime.Now
},
new Test
{
OwnerName = "ABCD",
OwnerId = 1,
status = "U",
ReleaseDates = DateTime.Now
},
new Test
{
OwnerName = "ABCD",
OwnerId = 1,
status = "S",
ReleaseDates = DateTime.Now
}
};
}
}