TheEmpty
TheEmpty

Reputation: 11

How to Combine two object into one in C#

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
                   };

In this LINQ query, when I need all the properties in result, I need to write every property in select new {}, is there a easy way to do this ?

Upvotes: 1

Views: 902

Answers (1)

Romano Zumbé
Romano Zumbé

Reputation: 8079

Put the two objects into the result object:

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
                   };

Then access the properties like so:

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

Update (OP wants to use all properties in the result directly):

You can get a list of all properties via reflection in the C# interactive window and construct a string output to paste into your code like this:

#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 is your assembly which could also be an exe

Upvotes: 4

Related Questions