2 回答
TA贡献1811条经验 获得超5个赞
也许有更简单的方法,但这是LINQ我写的第一个查询,至少应该足以让您入门。首先,我将您的问题和 appid 弄平,然后我按问题重新分组并按问题列出了您的 appid。请注意,您必须先填充您List的应用程序,然后才能运行。
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()
});
TA贡献1982条经验 获得超2个赞
我认为这个问题被描绘得有点过分。每个应用程序都应该有一个不同的AppId,所以基本上没有什么可以分组的,因为所有的AppIds 都是不同的。相反,我们应该按问题分组,因为每个应用程序都可能有相同的问题。
这是我所拥有的(就样式而言,它与确切的输出不匹配,因为您的示例输出基于按AppId而不是问题分组,但预期结果相同):
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
// create Questions
var questionOne = new Question(){QuestionId = 1, ActualQuestion = "Who"};
var questionTwo = new Question(){QuestionId = 2, ActualQuestion = "What"};
var questionThree = new Question(){QuestionId = 3, ActualQuestion = "Where"};
// Assign questions to the specified list of questions
var applicationOneQuestions = new List<Question>(){questionOne, questionTwo, questionThree};
var applicationTwoQuestions = new List<Question>() {questionOne, questionTwo};
var applicationThreeQuestions = new List<Question>() {questionOne, questionThree};
var applicationFourQuestions = new List<Question>() {questionOne};
// Create Applications
var applicationOne = new Application(){AppId = 1, Questions = applicationOneQuestions};
var applicationTwo = new Application(){AppId = 2, Questions = applicationTwoQuestions};
var applicationThree = new Application() {AppId = 3, Questions = applicationThreeQuestions};
var applicationFour = new Application() {AppId = 4, Questions = applicationFourQuestions};
// Create List of Applications
var lstApplications = new List<Application>(){applicationOne, applicationTwo, applicationThree, applicationFour};
// Group Applications based on Questions and cast to Section Object
var groupApplications = lstApplications.GroupBy(x => x.Questions).Select(t => new Section { AppIds = t.Select(z => z.AppId).ToList() , Questions = t.Key}).ToList();
foreach(var item in groupApplications)
{
foreach(var appId in item.AppIds)
{
Console.WriteLine(appId);
}
foreach(var question in item.Questions)
{
Console.WriteLine(question.ActualQuestion);
}
Console.WriteLine("\n");
}
}
}
public class Application
{
public int AppId { get; set; }
public List<Question> Questions { get; set; }
}
public class Section
{
public List<int> AppIds { get; set; }
public List<Question> Questions { get; set; }
}
public class Question
{
public int QuestionId {get;set;}
public string ActualQuestion {get;set;}
}
输出
// 1
// Who
// What
// Where
// 2
// Who
// What
// 3
// Who
// Where
// 4
// Who
申请 1、2、3、4 都包含问题一
应用程序 1、2 包含问题二
应用程序 1、3 包含问题三
请让我知道这可不可以帮你。我还为您创建了一个DotNetFiddle,供您自行测试并提供反馈。
- 2 回答
- 0 关注
- 186 浏览
添加回答
举报