英文:
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<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}
}
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<string> distinctPortfolioCodes = dto.AOrders
.Select(a => a.PortfolioCode)
.Union(dto.BOrders.Select(b => 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 => order.PortfolioCode)
.Concat(dto.BOrders.Select(order => 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论