根据ID列表更新对象列表中的属性

时间:2015-05-23 20:22:43

标签: c# linq left-join

两个清单。一个是代表我向其发送电子邮件的一组人的对象。为简洁起见,我们可以说结构是

public class EmailSent
{
    public int Id {get;set;}
    public string Email {get;set;}
    public bool HasResponse {get;set;}
}

它有我发送的每封电子邮件的支持表(减去HasResponse列)。我有另一个表存储所有响应。

public class EmailResponse
{
    public int Id {get;set;}
    public string Response {get;set;}
}

我有一个当前失败的测试,我无法弄清楚如何让它通过。在制作中我基本上用SELECT Id, Email from EmailSent where Id between @MinId and @MaxId之类的东西查询EmailSent表 没有什么花哨的。我的测试基本上是收益率返回,在每个数字之间执行单个EmailSent ...下一部分是我在该列表上做一个选择以给我Id并对EmailResponse进行第二次查询。 SELECT Id from EmailResponse WHERE Id in (...generate list of id's)在我的测试中,我写了

public IEnumerable<EmailResponse> GetEmailResponses(IEnumerable<long> Ids, int waveId)
{
    foreach (var id in Ids.Take(10))
    {
        yield return new EmailResponse {Id = id};
    }
}

令人心烦意乱的测试就是这个

   [Test]
    public void WhenAnEmailGroupIsSelectedSpecificInformationIsShown()
    {
        _viewModel.SelectedEmailGroup = _viewModel.EmailGroups[0];
        _viewModel.Emails.Count.Should().Be(286);
        _viewModel.Emails.Count(x => x.HasMatchingResult).Should().Be(10);
    }

这是错误的消息,预计10为计数,但找到0.我现在所拥有的是(为了清楚起见将变更改为IEnumerable)

IEnumerable<EmailGroup> emails = _dao.GetEmailsSent(SelectedEmailGroup);
IEnumerable<EmailResponse> results = _dao.GetEmailResponses(emails.Select(x => x.Id), SelectedEmailGroup.WaveId);
IEnumerable<EmailGroup> matches = emails.Join(results, x => x.Id, y => y.Id, (x, y) => x).ToList();
//matches.ForEach(x => x.HasMatchingResult = true); this is the line that probably needs to change
foreach (var email in emails)
{
    Emails.Add(email);
}

对我来说很明显有什么问题,但我无法弄清楚如何根据回复轻松更新电子邮件。请帮助:)

1 个答案:

答案 0 :(得分:1)

最可能的问题是,您["2015-02-19", "item10", "22"] ToList()没有emails,这意味着当您的单元测试要求时,它会再次重新生成。此时IEnumerable标志将丢失,因此您的测试将失败。修复此问题非常简单 - 只需将HasMatchingResult添加到发出ToList的来电,然后取消注释emails

ForEach

您无需在那里执行加入:您只需在IEnumerable<EmailGroup> emails = _dao.GetEmailsSent(SelectedEmailGroup).ToList(); 中选择匹配EmailGroup的{​​{1}}:

Id

此时,您可以致电responces,或者更好地浏览“普通”ISet<int> emailIdsWithResponses = new HashSet<int>(results.Select(r => r.Id)); IEnumerable<EmailGroup> matches = emails.Where(e => emailIdsWithResponses.Contains(e.Id)).ToList(); 循环中的项目,设置ForEach标记:

foreach
相关问题