如何在linq中使用union <anonymoustype>和List <order>的union

时间:2017-01-18 09:12:42

标签: c# linq asp.net-mvc-5

我有一个Linq代码如下:

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();  

我有一个如下的订单:

List<Order> order

this.order属性为orderIdorderDate

我想将这两个列表合并到一个列表中以获得{check_id,date,title,OrderId and OrderDate}并通过JSON发送该列表以进行查看

2 个答案:

答案 0 :(得分:2)

  

我想将Union用于checkList和List<Order>,但我不知道   怎么样。结果应为List<anonymous tpe>

嗯,那实际上很容易:

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

这假设Order中存在这些属性,但我确信你明白了。

如果您只需要第一个查询来“提供”联盟,那么可以提高效率,DistinctToList是不必要的,因为Union会删除重复项。

答案 1 :(得分:2)

For Making Union两个侧列名称必须相同。

// 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();