简体   繁体   English

如何将来自同一IQueryable的不同行分组

[英]How to group different rows from same IQueryable

I have an IQueryable that contains the list of usage data in my application. 我有一个IQueryable,其中包含应用程序中使用情况数据的列表。 Each row in it is a separate entry in the table. 表中的每一行都是一个单独的条目。 The structure is like this 结构是这样的

{ {

Usagedata 使用数据

Username (string) 用户名(字符串)
SessionId (string) SessionId(字符串)
PartOfAppAccessed PartOfAppAccessed
(
Key (int), 键(int),
Name (string), 名称(字符串),
Description (string) 说明(字符串)
Time (DateTime) 时间(DateTime)
)
} }

But while displaying this data, I want to group rows based on session Id's. 但是在显示此数据时,我想根据会话ID对行进行分组。 So my output has to be in this structure 所以我的输出必须是这种结构

{ {

Usagedata 使用数据

Username (string) 用户名(字符串)
SessionId (string) SessionId(字符串)
Time (DateTime) 时间(DateTime)
PartOfAppAccessed PartOfAppAccessed
(
Key (int), 键(int),
Name (string), 名称(字符串),
Description (string) 说明(字符串)
Time (DateTime) 时间(DateTime)
), ),
(
Key (int), 键(int),
Name (string), 名称(字符串),
Description (string) 说明(字符串)
Time (DateTime) 时间(DateTime)
), ),
(
Key (int), 键(int),
Name (string), 名称(字符串),
Description (string) 说明(字符串)
Time (DateTime) 时间(DateTime)
)
} }

So my question is - How do I group different rows from the same IQueryable based on some condition (such as common sessionId's in this case)? 所以我的问题是-如何根据某种条件(例如,在这种情况下为通用sessionId)将来自同一IQueryable的不同行分组?

I suppose that you want to group your UsageData instances based on their SessionId and UserName . 我想您要根据其SessionIdUserNameUsageData实例进行分组 The code: 编码:

IQueryable<UsageData> usageData = ... ;
var groupedUsageData = usageData.GroupBy(x => new { x.SessionId, x.Username });

Then, you can work with a single group like the following: 然后,您可以像下面这样使用单个组:

var singleGroup = groupedUsageData.ElementAt(0);
string sessionId = singleGroup.Key.SessionId;
string name = singleGroup.Key.Name;

IEnumerable<string> accessedAppsNames = singleGroup.Select(x => x.PartOfAppAccessed.Name);

A few notes that came to mind: 我想到了一些注意事项:

  • Since you can probably directly map the session to the user, it may be unnecessary to store both SessionId and Username in your UsageData objects. 由于您可能可以直接将会话映射到用户,因此可能没有必要将SessionIdUsername都存储在UsageData对象中。 Perhaps it would be better to store only SessionId and get the name of the user from some other table? 也许最好只存储SessionId并从其他表中获取用户名?
  • It doesn't make a sense for grouped UsageData to contain Time property. 分组的UsageData包含Time属性是没有意义的。 What value would it have? 它会有什么价值? In your original object (before the grouping takes place), the Time property is only declared on PartOfAppAccessed object. 在原始对象中(在进行分组之前),仅在PartOfAppAccessed对象上声明Time属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM