简体   繁体   English

获取列表C#中的下一项并更新当前项

[英]Get next item in list c# and update the current one

I have a list like this 我有这样的清单

List<NamazTimesModel> res = nt.Select();

In res I have data like this 在res中,我有这样的数据

[
{
"name": "fajr",
"salahTime": "05:23",
"namazTime": "05:23",
"date": "3/6/2017 12:00:00 AM",
"endTime": null
},
{
"name": "sunrise",
"salahTime": "07:01",
"namazTime": "07:01",
"date": "3/6/2017 12:00:00 AM",
"endTime": null
},
{
"name": "zuhr",
"salahTime": "12:33",
"namazTime": "12:33",
"date": "3/6/2017 12:00:00 AM",
"endTime": null
},
....
]

I am looping over the list and checking what is the current item. 我遍历该列表并检查什么是当前项目。 For example it is 'fajr' then I have to take the next item and get the 'salahTime' from there and set 'endTime' of fajr to be that. 例如,它是“ fajr”,那么我必须从下一个项目中获取“ salahTime”,然后将fajr的“ endTime”设置为该值。

Can I get some help? 我可以帮忙吗?

You can skip list items while your target item is not found, then grab the target item itself, along with the next one: 您可以在找不到目标项目时跳过列表项,然后获取目标项目本身以及下一个项目:

var twoItems = res.SkipWhile(item => item.Name != "fajr").Take(2).ToList();

If you have exactly two items in twoItems list, then you found fajr , and it wasn't the last item on the list. 如果在twoItems列表中恰好有两个项目,那么您找到了fajr ,它不是列表中的最后一个项目。 If you have fewer than two items, then either fajr wasn't there, or it was the last item on the list. 如果您的项目少于两个,则可能不是fajr ,或者它是列表中的最后一个项目。

Check that you have two items, and set fields as necessary: 检查您是否有两个项目,并根据需要设置字段:

if (twoItems.Count == 2) {
    twoItems[0].EndTime = twoItems[1].SalahTime;
}

Something like this should do it: 这样的事情应该做到:

   var res = nt.Aggregate(new List<NamazTimesModel>(), (t, i) =>
            {
                if (t.Count > 0)
                {
                    t[t.Count - 1].endTime = i.salahTime;
                }
                t.Add(i);
                return t;
            }
        );
for(int i = 1; i < res.Count; i++)
{
   // Todo: Check for null references by your own way.
   res[i - 1].endTime = res[i].salahTime;
}

You can set Namaz times as below, 您可以按以下方式设置Namaz时间,

for(var i = 0; i<nts.Count()-1; i++){
 nt[i].EndTime = nt[i+1].SalahTime
}

Then don't forget to set last Namaz time: 然后,别忘了设置Namaz的最后时间:

nts[nt.Count()-1] = nts[0].SalahTime;
res.ForEach(item =>
{
     int index = res.FindIndex(m => m.name == item.name);
     item.endTime = index+1 != res.Count ? res.ElementAt(index + 1).salahTime : res.FirstOrDefault().salahTime;
});;

You can do two iterations with linq query. 您可以使用linq查询进行两次迭代。

It will be like this: 它将是这样的:

string[] numbers= {"one","two","last"}; string[] variables={"string one","int two","string three"}; var res = variables.Where(v => numbers.Any(n => v.Contains(n ))); res.ToList().ForEach(d => Console.WriteLine(d));

working code here . 这里的工作代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM