当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - how to use union for List<anonymousType> and List<Order> in linq

问题描述:

I have a Linq code as below:

var checkList = (from dc in _debtorCreditorService.GetAllDebtorCreditors()

join n in _notificationService.GetAllNotification()

on dc.MaturityDate equals n.CreatedDate

where n.CreatedDate.Day == today.Day

select new

{

chek_id = n.TypeId,

date = n.CreatedDate,

title = n.Title

})

.Distinct()

.ToList();

and I have an order list like below:

List<Order> order

Where this.order properties are orderId and orderDate

I want to merge these two lists in one list to have {check_id,date,title,OrderId and OrderDate} and send that list by JSON to view

网友答案:

For Making Union Both the side columns name must be same .

// First Collect CheckList
var checkList = (from dc in _debtorCreditorService.GetAllDebtorCreditors()
                 join n in _notificationService.GetAllNotification() 
                 on dc.MaturityDate equals n.CreatedDate
                 where n.CreatedDate.Day == today.Day                    
                 select new Order
                 { 
                     chek_id = n.TypeId, 
                     date = n.CreatedDate, 
                     title = n.Title ,
                     OrderId=0,
                     OrderData=null
                 })
                 .Distinct()
                 .ToList(); 

// Secondly ,Collect Orders
var lstOrder=(from n in Order 
            select new Order
            {
                 chek_id = n.TypeId, 
                 date = n.CreatedDate, 
                 title = n.Title ,
                 OrderId=n.OrderId,
                 OrderData=n.OrderDate
            });

// Finally ,Make Union of both the Table            
var result=checkList.Union(lstOrder).Tolist();
网友答案:

I want to use Union for checkList and List<Order> but i don't know how. The result should be a List<anonymous tpe>

Well, then it's actually very easy:

var orders = orderList.Select(o => new 
                 { 
                     chek_id = o.TypeId, 
                     date = o.CreatedDate, 
                     title = o.Title 
                 });
var resultList = checkList.Union(orders).ToList();

This presumes that those properties exist in Order, but i'm sure you got the point.

If you only need your first query to "feed" the union you could make it more efficient, the Distinct and ToList are unnecessary because Union removes duplicates.

分享给朋友:
您可能感兴趣的文章:
随机阅读: