如何在C#中将两个对象合并为一个

时间:2017-05-31 07:43:42

标签: c# linq

var taskMessages = from d in result
                   join ptask in db.ListingTask.Entites on new
                   {
                       d.Id,
                       TaskType = ListingTaskType.Offer.ToString()
                   } equals new
                   {
                       Id = ptask.DraftId,
                       ptask.TaskType
                   } into temp
                   from t in temp.DefaultIfEmpty()
                   select new 
                   {
                       DraftId = d.Id,
                       OfferMessage = t == null || string.IsNullOrEmpty(t.Message) ? "无" : t.Message,
                       OfferSubmitResult = t == null || string.IsNullOrEmpty(t.Result) ? "无" : t.Result,
                       d.UserName,
                       d.UpdateTime,
                       d.Stock
                   };

在这个LINQ查询中,当我需要结果中的所有属性时,我需要在select new {}中编写每个属性,有没有一种简单的方法可以做到这一点?

1 个答案:

答案 0 :(得分:4)

将两个对象放入结果对象中:

var taskMessages = from d in result
                   join ptask in db.ListingTask.Entites on new
                   {
                      d.Id,
                      TaskType = ListingTaskType.Offer.ToString()
                   } equals new
                   {
                       Id = ptask.DraftId,
                       ptask.TaskType
                   } into temp
                   from t in temp.DefaultIfEmpty()
                   select new 
                   {
                       // you would obviously need better names
                       object1 = t,
                       object2 = d
                   };

然后访问这样的属性:

taskMessages[0].object2.UpdateTime; //Just as an example

更新(OP希望直接使用结果中的所有属性):

您可以通过C#交互式窗口中的反射获取所有属性的列表,并构造一个字符串输出以粘贴到您的代码中,如下所示:

#r "C:/MyApp/bin/Debug/Foo.dll"
using MyApp;
var myType = typeof(Person);
var myProperties = myType.GetProperties();
foreach(var myProperty in myProperties) { Console.WriteLine($"{myProperty.Name} = myObject.{myProperty.Name},"); }

Foo.dll是你的程序集,也可以是exe