c# - Linq Union,避免空数据和重复数据

标签 c# linq union

我正在尝试编写一个 linq 查询来合并 2 个集合,其解释如下:

public class VoteData
{
    public string Name{get;set;}
    public string VoteFunction  {get;set;}
    public string Area {get;set;}
    public string Sector {get;set;}
    public string Email {get;set;}
    public string VoterEmail {get; set;}
}

public class DirectoryData
{ 
   public string VoteFunction  {get;set;}
   public string Area {get;set;}
   public string Sector {get;set;}
   public string PrimaryEmail {get;set;}    
   public string VoterEmail {get; set;}

}

Linq 查询:

 var result = (from r in voteList select new { r.Email, r.Area, r.Sector, r.VoteFunction }).Union
              (from d in directoryDataList select new { Email = d.PrimaryEmail, d.Area, d.Sector, d.VoteFunction });

现在假设这个查询返回这样的结果:

No  Email        Area        Sector      VoteFunction  Voter Email
======================================================================
1.  abc@gmail    USA         IT          Sales         voter2@gmail
2.  abc@gmail    Null        IT          Analyst       voter2@gmail
3.  abc@gmail    USA         IT          null          voter2@gmail
4.  abc@gmail    Europe      Tech        null          voter2@gmail
5.  abc@gmail    Europe      Accounts    Analyst       voter2@gmail
6.  abc@gmail    Europe      null        Analyst       voter2@gmail
7.  abc@gmail    USA         IT          null          voter1@gmail
======================================================================

还有一个字段VoterEmail。所以基本上,我想计算每个 AreaSectorVoteFunction 的选票。 现在在上面的结果中,我想排除第 3 号结果和第 6 号结果。第 3 号结果因为它有区域和扇区,对于同一选民,它也存在于第 1 号结果中,而我仍然想保留第 7 号结果,因为它有不同的选民。与结果 6 类似,它具有区域和 voteFunction,这也存在于结果 5 中。

有什么解决办法吗?

最佳答案

因此,您想要对(区域、部门、选民电子邮件)具有相同值的项目进行分组。如果这些组中的任何一个包含多个项目,那么显然您有多个具有相同值(区域、部门、选民电子邮件)的对象,而您只想保留其中一个。

你说你想排除 3 因为它与 1 具有相同的值。同样我可以说我想排除 1 因为它与 3 具有相同的值。你关心它是 1 还是 3 ,或者我可以只选择其中的任何一个吗?

var finalResult = unionResult
    .GroupBy(item => new     // make groups of items with same Area / Sector / VoterEmail
    {
        Area = item.Area,
        Sector = item.Sector,
        VoterEmail = item.VoterEmail,
    });
    // all items in every group have the same Area/Sector/VoterEmail
    .Select (group => group.First()); // from every group take the first one

关于c# - Linq Union,避免空数据和重复数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49974358/

相关文章:

c# - 简单序列生成?

Mysql从多个存储过程创建一个存储过程

mysql - 混合 RAND() 和 UNION 给出随机行数?

mysql - 是 UNION、AND、OR 吗?

c# - 如何将 IoC 容器传递给 NancyFX? (欧文,团​​结)

c# - XNA - 缺少视频和视频播放器的命名空间?

c# - 在 .NET 中使用属性的性能开销

c# - C# 中超短且很棒的变量名

c# - 具有通用 ID 的通用存储库 - 如何在 int 时检索

linq - 这个 RavenDB linq 查询是如何工作的