我的问题基于this SO帖子。这有助于我返回null,但是如何为特定字段返回null
实施例
select new FlowerMetaData
{
FlowerId = flowers.FlowerId,
UpdatedDate = flowers.UpdatedDate,
FlowerDates = FlowerDates.OrderBy(d => d.CreatedDate).ToList(),
ClosedDate = FlowerDates
.Where(c => c.FlowerType == "Rainbow Rose" || c.FlowerType == "Black Rose" || c.FlowerType == "SunFlower" || c.FlowerType == "Lotus" || c.FlowerType == "Tulip" || c.FlowerType == "Rose")
.Any()
? flowersDates.Where(c => c.FlowerType == "Rainbow Rose" || c.FlowerType == "Black Rose" || c.FlowerType == "SunFlower" || c.FlowerType == "Lotus" || c.FlowerType == "Tulip" || c.FlowerType == "Rose").OrderByDescending(x => x.CreatedDate).Select(x => x.CreatedDate).FirstOrDefault()
: (DateTime?)null
}).FirstOrDefault();
我想仅在关闭日期返回null。
答案 0 :(得分:1)
您只能使用FirsOrDefault
:
...
ClosedDate = FlowerDates.Where(c =>new string[] {"Rainbow Rose",
"Black Rose",
"SunFlower",
"Lotus",
"Tulip",
"Rose"}.Contains( c.FlowerType))
.OrderByDescending(x => x.CreatedDate)
.Select(x =>(DateTime?) x.CreatedDate)
.FirstOrDefault(),
也是当你有这么多或条件好的时候使用Contains
扩展方法。如果没有符合条件的元素,则结果为null
。
答案 1 :(得分:1)
您的代码基本上已经在运行,但是有很多令人费解的代码混淆了这个问题。
我认为你的问题归结为根据ClosedDate
评估为真的有条件地设置Any()
:
void Main()
{
var FlowerDates = new List<Flower>();
FlowerDates.Add(new Flower {FlowerId =1});//Comment this out and you will get NULL
FlowerDates.Add(new Flower {FlowerId =2});
//I simplified the condition to focus on choosing a null value
//If Any() evaluates to true then get current time, else return null
//Yes you are doing a projection here, but setting a variable is effectively the same thing and simpler to follow
var ClosedDate = FlowerDates.Where(c => c.FlowerId == 1)
.Any()
? DateTime.Now
: (DateTime?)null;
//ClosedDate is either NULL or DateTime.Now depending on Any()
}
public class Flower
{
public int FlowerId { get; set; }
}