gpt4 book ai didi

c# - C#中如何将两个对象合二为一

转载 作者:太空宇宙 更新时间:2023-11-03 21:02:21 24 4
gpt4 key购买 nike

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 {} 中编写每个属性,有没有简单的方法可以做到这一点?

最佳答案

将两个对象放入result对象中:

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

关于c# - C#中如何将两个对象合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44278644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com