2017-05-31 28 views
1
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 {},有沒有簡單的方法來做到這一點?如何合併兩個Object成一個在C#

+0

您正在使用匿名查詢。如果您有預定義的類,則可以擁有消息類和用戶類,並具有包含用戶和消息屬性的任務類。 – jdweng

回答

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

+0

但是,我想把所有的屬性都放到select {}中,因爲我不想修改我的UI。 – TheEmpty