合并两个列表和匹配值

时间:2016-05-25 22:28:54

标签: c#

“Distributions”变量内部是一个名为“Deadline”的键,其中包含一个日期。

我想添加“RealDeadline = i.Deadline”。所有其他线路工作正常,但我无法找到添加最后一件事的方法。

匹配必须在AssignmentId上进行,AssignmentId是整个组合的关键。基本上如果HandInData.Where(...)只能从“发行版”中添加“截止日期”的值,那就可以解决问题..

var HandInData = db.Handins.ToList();
var Distributions = db.Distributes.ToList();

var AssignNames = HandInData.Where(a => Distributions.Any(x => x.AssignmentId == a.AssignmentId));

var StudentsHandedInDataFeed = AssignNames.Select(i => new {
    *RealDeadline = i.Deadline, (this is not working..)*
    Help = i.NeedHelp,
    Done = i.Done,
    AssName = i.Assignment.AssignmentName,
    Student = i.Student.StudentName,
    DeadlineInTimeformat = i.Assignment.AssignmentDeadline,
    HandedInInTimeformat = i.HandedInDate,
    Deadline = i.Assignment.AssignmentDeadline.ToString(),
    HandedIn = i.HandedInDate.ToString()
});


public class Handin {
    public int HandinId { get; set; }
    public int StudentId { get; set; }
    public int AssignmentId { get; set; }

    public bool? Done { get; set; }
    public bool? NeedHelp { get; set; }

    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? HandedInDate { get; set; }

    public virtual Student Student { get; set; }
    public virtual Assignment Assignment { get; set; }

}

1 个答案:

答案 0 :(得分:2)

您需要加入这两个列表。您可以使用LINQ语法执行此操作:

var StudentsHandedInDatFeed = 
    from h in HandInData
    join d in Distributions on h.AssignmentId equals d.AssignmentId
    select new {
        RealDeadline = d.Deadline,
        Help = h.NeedHelp,
        // etc
    };

联接只会包含来自HandInData的{​​{1}}中匹配值的值,因此这也会照顾您的Distributions代码。