不同类型的集合中不同

huangapple go评论63阅读模式
英文:

Distinct across different types of collection

问题

这是对象图:

public class Dto
{
  public List<OrderTypeA> AOrders { get; set; }
  public List<OrderTypeB> BOrders { get; set; }
}
public class OrderTypeA
{
  public string PortfolioCode { get; set; }
}
public class OrderTypeB
{
  public string PortfolioCode { get; set; }
}

如何从Dto对象的AOrders集合和BOrders集合中查找不同的portfolioCode?将其添加到列表然后在列表上执行distinct操作相对简单,但是否有一个使用LINQ的一行代码解决方法?

英文:

Here's the object graph

public class Dto
{
  public List&lt;OrderTypeA&gt; AOrders {get;set;}
  public List&lt;OrderTypeB&gt; BOrders {get;set;}
}
public class OrderTypeA
{
  public string PortfolioCode {get;set}
}
public class OrderTypeB
{
  public string PortfolioCode {get;set}
}

How do I find distinct of portfolioCode(s) from Dto object across AOrders collection and BOrders colection. Its fairly easy adding it to a list and then doing distinct on the list but is there a one liner with linq

答案1

得分: 4

List<string> distinctPortfolioCodes = dto.AOrders
    .Select(a => a.PortfolioCode)
    .Union(dto.BOrders.Select(b => b.PortfolioCode))
    .ToList();

当我们执行 Union 操作时,我们只获取 OrderTypeA 和 OrderTypeB 的不重复值。

快速而简单。
英文:
List&lt;string&gt; distinctPortfolioCodes = dto.AOrders
    .Select(a =&gt; a.PortfolioCode)
    .Union(dto.BOrders.Select(b =&gt; b.PortfolioCode))
    .ToList();

When we do a Union we only get the distincts value of both OrderTypeA, and OrderTypeB.

Quick and dirty.

答案2

得分: 1

首先,从AOrders集合中创建一个包含所有投资组合代码的序列(dto.AOrders.Select),然后将此序列与BOrders集合中的所有投资组合代码序列连接(.Concat)。最后,我们将在生成的序列上调用Distinct()方法(现在该序列的类型仅为string),以去除任何重复项。

英文:
var distinctPortfolioCodes = dto.AOrders.Select(order =&gt; order.PortfolioCode)
  .Concat(dto.BOrders.Select(order =&gt; order.PortfolioCode))
    .Distinct();

first create a sequence of all the portfolio codes from the AOrders collection.( dto.AOrders.Select) then concatenate( .Concat) this sequence with a sequence of all the portfolio codes from the BOrders collection. Finally, we will call the Distinct() method on the resulting sequence(which is now only of type string) to remove any duplicate

huangapple
  • 本文由 发表于 2023年6月12日 19:14:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76456107.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定