将多行组合到对象属性中

时间:2012-09-10 10:59:43

标签: c# asp.net-mvc json linq

我有一个SQL查询,它返回使用日志中的行,如:

ActionID    ActionType      ActionDetail    ActionDetailValue
1           SEARCH          Query           jones
1           SEARCH          ResultCount     156
2           DOCUMENT_VIEW   Title           All About Mister Jones
2           DOCUMENT_VIEW   DocumentID      EKDJF34

即。用户采取的每个动作可能有多行,其中包含有关所采取操作的不同细节。目前,这在C#中表示为:

IEnumerable<ActionItem>

public class ActionItem
{
    public int ActionID { get; set; }
    public string ActionType { get; set; }
    public string ActionDetail { get; set; }
    public string Value { get; set; }
}

我需要以某种方式组合具有相同id和类型的行。最后,我想要返回一个JSON对象:

var trailItems = {"trailitems": [
    {"ActionID": "1", "ActionType": "SEARCH", "Query": "jones", "ResultCount" : "156"},
    {"ActionID": "2", "ActionType": "DOCUMENT_VIEW", "Title": "All About Mister Jones", "DocumentID" : "EKDJF34"}
]};

看起来像LINQ的工作?

1 个答案:

答案 0 :(得分:0)

我不会过多地开发Json部分,我认为当你拥有足够好的数据结构时,你将能够处理它。你可以试试这个:

var grouped = 
    from a in actions
    group a by new { a.ActionID, a.ActionType } 
    into g
    select new 
    { 
        g.Key.ActionID, 
        g.Key.ActionType, 
        Values = 
            (from x in g
             select new KeyValuePair<string, string>(x.ActionDetail, x.Value))
            .ToDictionary()
    };

如果您尝试从此构建json而无需进一步处理,您将获得以下内容:

[
    {"ActionID":1,"ActionType":"SEARCH","Values":{"Query":"jones","ResultCount":"156"}},
    {"ActionID":2,"ActionType":"DOCUMENT_VIEW","Values":{"Title":"All About Mister Jones","DocumentID":"EKDJF34"}}
]

这不是你想要的,但它非常接近,也许处理起来会更好,因为它将'键'与值分开。