反正我是否可以停止转换两次?
allObjects.Where(x =>
Convert.ToDateTime(x.MyDate).DayOfWeek != DayOfWeek.Saturday &&
Convert.ToDateTime(x.MyDate).DayOfWeek != DayOfWeek.Sunday).ToList()
假设我无法改变" MyDate"到datetime停止必须首先进行转换
答案 0 :(得分:3)
对于这些类型的案例,使用查询理解表格通常更容易。
var q = from obj in allObjects
let day = Convert.ToDateTime(obj.MyDate).DayOfWeek
where day != DayOfWeek.Saturday
where day != DayOfWeek.Sunday
select obj;
var result = q.ToList();
请注意,Tim Schmelter给出的答案是该查询的流畅形式;我发现理解形式更容易阅读和推理。
答案 1 :(得分:2)
假设我无法将“MyDate”的类型更改为停止的日期时间 必须首先进行转换
你为什么这么认为?那将是最好的选择
如果您不能这样做,您可以将结果存储为匿名类型:
var objectList = allObjects
.Select(x => new { Object = x, Date = Convert.ToDateTime(x.MyDate) })
.Where(x => x.Date.DayOfWeek != DayOfWeek.Saturday && x.Date.DayOfWeek != DayOfWeek.Sunday)
.Select(x => x.Object)
.ToList();
答案 2 :(得分:1)
制作帮助扩展方法将使您的查询更具可读性:
static class DayOfWeekExtensions {
public static bool IsWeekEnd(DayOfWeek dow) {
return dow == DayOfWeek.Saturday || dow == DayOfWeek.Sunday;
}
}
现在您的查询可以按如下方式重写:
var notOnWeekEnds = allObjects
.Where(x => !Convert.ToDateTime(x.MyDate).DayOfWeek.IsWeekEnd())
.ToList()
答案 3 :(得分:0)
你可以这样做:
allObject.Where(x => { var dt = Convert.ToDateTime(x.MyDate);
return dt.DayOfWeek != DayOfWeek.Saturday && dt.DayOfWeek != DayOfWeek.Sunday;
}).ToList();
答案 4 :(得分:0)
是 -
allObjects.Where(x => {
var dateConvered = Convert.ToDateTime(x.MyDate);
return dateConvered .DayOfWeek != DayOfWeek.Saturday && dateConvered.DayOfWeek != DayOfWeek.Sunday; }).ToList();
答案 5 :(得分:0)
我可能会走这条路。我讨厌多个OR逻辑。
var allObjects = new List<Foo>
{
new Foo { MyDate = "3/10/18" },
new Foo { MyDate = "3/11/18" },
new Foo { MyDate = "3/12/18" },
new Foo { MyDate = "3/13/18" },
new Foo { MyDate = "3/14/18" }
};
var valuesToRemove = new DayOfWeek[]
{
DayOfWeek.Saturday, DayOfWeek.Sunday
};
var list = allObjects.Where //<-- This is the part that will interest you
(
x => Array.IndexOf
(
valuesToRemove,
Convert.ToDateTime(x.MyDate).DayOfWeek
) == -1
);
Console.WriteLine(string.Join("\r\n", list));
输出:
3/12/18
3/13/18
3/14/18
答案 6 :(得分:0)
这对于在LINQ表达式中重用计算值可能没有帮助,但在您的特定情况下,您可以将其重写为:
var weekendDays = new [] { DayOfWeek.Saturday, DayOfWeek.Sunday };
var weekdayObjects = allObjects.Where(x =>
!weekendDays.Contains(Convert.ToDateTime(x.MyDate).DayOfWeek)
).ToList();