根据列表中的元素对同一对象进行分组 [英] Grouping the same object according to the elements of their lists

查看:89
本文介绍了根据列表中的元素对同一对象进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类型为Application的对象的列表,如下所示:

I have following list of the objects of type Application, which looks like:

public class Application
    {
        public int AppId { get; set; }
        public List<Question> Questions { get; set; }
    }

我想做的就是将它们映射到Section类型的对象,如下所示:

What I want to do is to map them to object of type Section looking like:

public class Section
       {
            public List<int> AppIds { get; set; }
            public List<Question> Questions { get; set; }
        }

通过按照以下规则将它们分组:在包含这些问题的AppId列表下收集所有相同的问题.示例输入和输出:

by grouping them according to following rule: gather all the same questions under the lists of AppIds, which contain these questions. Exemplary Input and Output:

Input: A1(Q1,Q2,Q3), A2(Q1,Q2), A3(Q1,Q3), A4(Q1). 
Output: A1,A2,A3,A4(Q1), A1,A2(Q2), A1,A3(Q3)

有可能在LINQ中做到吗?还是我必须自己编写逻辑?

Is that possible to do it in LINQ? Or I have to write logic on my own?

推荐答案

也许有更简单的方法,但这是我编写的第一个LINQ查询,至少应该足以使您入门.首先,我将您的问题和appid弄平,然后按问题重新组合,然后按问题列出您的appid.请注意,您必须先填充List应用程序,然后该程序才能运行.

Maybe there is a simpler way, but this is the first LINQ query I wrote and should be enough to at least get you started. First I flattened out your questions and appids, then I regrouped by questions and listed your appids by question instead. Note that you'll have to populate your List of applications before this will run.

List<Application> app = new List<Application>();
var output = (from a in app.SelectMany(p => p.Questions.Select(z => new {z, p.AppId})
group a.AppId by new 
{
a.Questions
} into combined
select new 
{
combined.Key.Questions,
combined.ToList()
});

这篇关于根据列表中的元素对同一对象进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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