我有一个列表,其中包含Time
属性的项目。如果我想选择Time
等于或大于startTime
的所有项目,那么我会写下这样的内容:
var newList = list.Where(i => (i.Time >= startTime));
但现在我也想得到最后一项,时间小于startTime
。有没有更好的方法来实现这个?
例如,我列出了此列表中项目有Time
的列表:
[5:32, 5:46, 5:51, 6:07, 6:11, 6:36]
我们将startTime
指定为6:00
。
现在我们想要得到这个时间:
[5:51, 6:07, 6:11, 6:36]
答案 0 :(得分:3)
立即获取整个列表:
var newList = list
.OrderByDescending(i => i.Time)
.Take(list.Count(j => j.Time >= startTime) + 1)
.OrderBy(k => k.Time); //Optional
有认知的建议:
var newList = list
.OrderBy(i => i.Time)
.Skip(list.Count(j => j.Time < startTime - 1));
答案 1 :(得分:1)
var smallerThan = list
.Where(i => i.Time < startTime)
.OrderByDescending(o => o.Time)
.Take(1)
.Concat(list.Where(i => i.Time => startTime));
答案 2 :(得分:1)
PROJECT_ID
或
var result=list
.Where(i=>i.Time<startTime)
.OrderBy(i=>i.Time)
.Last()
.Concat(list
.OrderBy(i=>i.Time)
.Where(i=>i.Time>=startTime)
);
答案 3 :(得分:1)
由于您的列表是您想要查找的属性的顺序,您可以按照
的顺序执行操作List<int> things = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };
int threshold = 4;
var newThings = things.Skip(things.FindIndex(x => x >= threshold) - 1);
Console.WriteLine(string.Join(", ", newThings));
哪个输出
3,4,5,6,7,8
扩展它以使用具有Time
属性的类恰好是TimeSpan
:
class Z
{
public TimeSpan Time { get; set; }
};
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
List<Z> zs = new List<Z>();
for (int i = 0; i < 10; i++)
{
zs.Add(new Z { Time = new TimeSpan(i, rand.Next(0,61), rand.Next(0,61)) });
}
TimeSpan threshold = new TimeSpan(4,0,0);
var newThings = zs.Skip(zs.FindIndex(x => x.Time >= threshold) - 1);
Console.WriteLine(string.Join(", ", newThings.Select(x => x.Time.ToString("c"))));
Console.ReadLine();
}
}
示例输出:
03:03:57,04:09:37,05:14:44,06:58:55,07:40:33,08:37:06,09:10:06
答案 4 :(得分:1)
许多答案似乎需要降序。但是你可以通过干净的衬里和良好的效率轻松避免这种情况:
var newList = list.Skip(list.Count(j => j.Time < startTime) - 1);
答案 5 :(得分:0)
var newList = list
.Where(i => (i.Time >= startTime))
.ToList()
.Add(list
.Where(i => (i.Time < startTime))
.OrderByDescending(o => o.Time)
.FirstOrDefault()
)
答案 6 :(得分:0)
int lastItemIndex = list.OrderBy(D => D.TimeOfDay).ToList()
.FindLastIndex(D => D.TimeOfDay < startTime);
var newList = list.Where(D => list.IndexOf(D) > lastItemIndex);