如何编写这个LINQ查询

时间:2013-05-14 06:13:34

标签: c# winforms linq

我有一个包含以下字段的数据表

DAT_START
GROUPBY
TXT_LATITTUDE
TXT_LONGITUDE
INT_DIRECTION
INT_CALL_DATA_TYPE
LNG_DURATION

以下是我正在使用的LINQ查询

var data = (from r in dt.AsEnumerable()
where ((r.Field<DateTime>("DAT_START").TimeOfDay.Hours < 20) && (r.Field<DateTime>("DAT_START").TimeOfDay.Hours >= 4))
group r by new { CID = r["GroupBy"], CLatitude = r["TXT_LATITUDE"], CLongitude = r["TXT_LONGITUDE"],CDirection = r["INT_DIRECTION"], 
CCallType = r["INT_CALL_DATA_TYPE"],CDuration = r["LNG_DURATION"] }
into groupedTable
select new
{
   CellID = groupedTable.Key.CID,
   CallCount = groupedTable.Count(),
   Longitude = groupedTable.Key.CLongitude,
   Latitude = groupedTable.Key.CLatitude,
   Direction = groupedTable.Key.CDirection,
   CallType = groupedTable.Key.CCallType,
   Duration = groupedTable.Key.CDuration
}).OrderByDescending(s => s.CallCount);

它给我这样的结果

CellID = 4057,CallCount = 84,Longitude = "",Latitude = "",Direction = "Incoming",CallType = "Voice",Duration = 50
CellID = 4057,CallCount = 8,Longitude = "",Latitude = "",Direction = "Outgoing",CallType = "Voice",Duration =97
CellID = 4057,CallCount = 56,Longitude = "",Latitude = "",Direction = "Incoming",CallType ="SMS" ,Duration = 0
CellID = 4057,CallCount = 41,Longitude = "",Latitude = "",Direction = "Outgoing",CallType = "SMS",Duration = 0

现在我想要这样的结果

CellID = 4057, TotalCommCount = 204, TotalDuration = 147, INSMSCount = 56,OutSMSCount = 41, INVoiceCount = 84,OutVoiceCount = 8,InVoiceDuration =50,OutVoiceDuration = 47

我该怎么办?我很震惊......

2 个答案:

答案 0 :(得分:6)

此时看起来你的分组太多了,这就是你要获得多行的原因。我怀疑你想要这样的东西:

from r in dt.AsEnumerable()
where r.Field<DateTime>("DAT_START").TimeOfDay.Hours < 20 && 
      r.Field<DateTime>("DAT_START").TimeOfDay.Hours >= 4
group r r["GroupBy"] into g         
select new
{
    CellID = g.Key,
    TotalCommCount = g.Count(),
    TotalDuration = g.Sum(r => r.Field<long>("LNG_DURATION")),
    InSMSCount = g.Count(r => r.Field<string>("DIRECTION") == "Incoming" &&
                              r.Field<string>("CALL_TYPE") == "SMS"),
    OutSMSCount = g.Count(r => r.Field<string>("DIRECTION") == "Outgoing" &&
                               r.Field<string>("CALL_TYPE") == "SMS"), 
    InVoiceCount = g.Count(r => r.Field<string>("DIRECTION") == "Incoming" &&
                                r.Field<string>("CALL_TYPE") == "Voice"),
    OutVoiceCount = g.Count(r => r.Field<string>("DIRECTION") == "Outgoing" &&
                                 r.Field<string>("CALL_TYPE") == "Voice"),
    InVoiceDuration = g.Where(r => r.Field<string>("DIRECTION") == "Incoming" &&
                                r.Field<string>("CALL_TYPE") == "Voice")
                       .Sum(r => r.Field<long>("DURATION"))
    OutVoiceDuration = g.Where(r => r.Field<string>("DIRECTION") == "Outgoing" &&
                                    r.Field<string>("CALL_TYPE") == "Voice"),
                       .Sum(r => r.Field<long>("DURATION"))
 } into summary
 order by summary.TotalCommCount descending
 select summary;

答案 1 :(得分:0)

我建议您在SQL数据库中创建一个视图,您可以在其中简单地聚合您需要的内容,然后在Linq查询中使用该视图 - 这将快速执行并且很容易编写。

设计草图:

由于您对要求的描述并不完全清楚,我已做出假设。 创建 SQL视图,例如(只是为了显示想法,根据您的需要进行更改):

CREATE VIEW [dbo].[vSumDurations]
AS 
select  c.CellId, j1.SumDuration1 as TotalDuration, 
        j2.SumDuration2 as GroupedDuration, j1.CallCount  
from (select distinct t.CID as CellId from [dbo].[YourTable] t) c
left join (select t1.CID as CellId, sum(LNG_Duration) as SumDuration1, 
            count(*) as CallCount from [dbo].[YourTable] t1 
            Group By t1.CID) j1 
on c.CellId=j1.CellId           
left join (select t2.CID as CellId, sum(LNG_Duration) as SumDuration2 
            from [dbo].[YourTable] t2 
            Group by t2.CID, t2.Direction, t2.CallType) j2 
on c.CellId=j2.CellId

(您知道可以通过在实体图页面的上下文菜单中使用“从数据库更新模型”轻松地将此视图添加到* .EDMX,然后在“tables / views”部分中勾选视图vSumDurations弹出的对话框。)

完成此准备后, Linq查询非常简单,因为视图中已经完成了所有内容。因此,代码看起来像:

var dc = this; // in LinqPad you can set your data context
var data = (from d in dc.vSumDurations select d).OrderByDescending(s => s.CallCount);
data.Dump();

注意:示例是针对LinqPad的 - 您需要在实际代码中使用不同的数据上下文。 Linqpad不需要dc,但如果您出于方便原因而声明它会更容易,因为在您的真实代码中您必须提供它。