给出以下c#代码:
public class Class1
{
public static void Main()
{
var tasks = new[]
{
new Task {id = 1, name = "Task 1", dependencyId = 0},
new Task {id = 2, name = "Task 2", dependencyId = 1},
new Task {id = 3, name = "Task 3", dependencyId = 2},
new Task {id = 4, name = "Task 4", dependencyId = 3},
new Task {id = 5, name = "Task 5", dependencyId = 0},
};
var listOfTasks = (from t in tasks
join dt in tasks
on t.id equals dt.dependencyId into JoinedTasks
from jt in JoinedTasks
select new TaskWithDependency
{
Task = jt,
DependentTask = t
}).ToList();
foreach (var z in listOfTasks)
{
Console.WriteLine(z.Task.name + " depends on: " + (z.DependentTask != null ? z.DependentTask.name : ""));
}
Console.ReadKey();
}
}
public class TaskWithDependency
{
public Task Task { get; set; }
public Task DependentTask { get; set; }
}
public class Task
{
public int id { get; set; }
public string name { get; set; }
public int dependencyId { get; set; }
}
如何使用LINQ投射到IEnumerable<TaskWithDependency>
。我正在有效地尝试实现自我加入。结果应该是IEnumerable<TaskWithDependency>
,在此示例中,只有第一个TaskWithDependency
具有依赖关系。
答案 0 :(得分:2)
var tasksTransformed = tasks.Select(x => new TaskWithDependency
{
Task = x,
DependentTask = tasks.Where(y => y.DependencyId == x.id)
}
答案 1 :(得分:0)
这可能是您正在寻找的:
IEnumerable<TaskWithDependency> tasksWithDep = tasks.Select(t => new TaskWithDependency() { Task = t, DependentTask = tasks.Where(dt => dt.dependencyId == t.id) });