我想要一个基于entityframework方法的查询 [英] I want a query of entityframework method based

查看:107
本文介绍了我想要一个基于entityframework方法的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张如下表格

比特AId 
true 1
false 1
false 2
true 2
true 1
false 3
true 1
false 3
false 1
true 2
true 1
true 3
false 3
true 2



假设上表的相应实体为A.



I想要一个查询entityframework方法,它基于每个唯一的AId减去false的计数。如下所示

比特AId 
2 1
2 2
-2 3

解决方案

这样的事情怎么样:

 IDictionary< int,int> result = context.A 
.GroupBy(a = > a.AId,(AI,list)= > new
{
AId,
TrueCount = list.Count(i = > i.Bit),
FalseCount = list.Count(i = > !i.Bit)
})
.ToDictionary(x = > x.AId,x = > x.TrueCount - x.FalseCount)
;





编辑:字典不保留元素的顺序。如果你想使用 OrderBy ,你需要使用差异收集类型。



  var  result = context.A 
.GroupBy(a = > a.AId,(AI,list)= > new
{
AI,
Count = list.Count(i = > i.Bit) - list.Count(i = > !i.Bit)
})
.OrderBy(x = > x.Count)
.ToList()
;

// result现在包含匿名类型的排序列表,
// 每个都有AId和Count属性。


I have a table like below

Bit	AId
true	1
false	1
false	2
true	2
true	1
false	3
true	1
false	3
false	1
true	2
true	1
true	3
false	3
true	2


suppose corresponding entity for above table is A.

I want a query entityframework method based that it subtract count of true from count of false for every unique AId. like below

Bit    AId
2      1
2      2
-2     3

解决方案

How about something like this:

IDictionary<int, int> result = context.A
    .GroupBy(a => a.AId, (AId, list) => new 
    { 
        AId, 
        TrueCount = list.Count(i => i.Bit), 
        FalseCount = list.Count(i => !i.Bit) 
    })
    .ToDictionary(x => x.AId, x => x.TrueCount - x.FalseCount)
;



Edit: Dictionaries do not preserve the order of the elements. If you want to use OrderBy, you'll need to use a difference collection type.

var result = context.A
    .GroupBy(a => a.AId, (AId, list) => new
    {
        AId,
        Count = list.Count(i => i.Bit) - list.Count(i => !i.Bit)
    })
    .OrderBy(x => x.Count)
    .ToList()
;

// "result" now contains a sorted list of anonymous types,
// each of which has the properties "AId" and "Count".


这篇关于我想要一个基于entityframework方法的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆