[英]LINQ Select n list ASP.NET Core
I have this code:我有这段代码:
foreach(var i in category.count)
{
var getDifferentSerialNumberforEachLoop = _db.Category.Where(a => a.CategoryID ==
categoryID).Select(i=>i.SerialNumber).FirstOrDefault();
//Proceed to do something else with the first serial number value
.....
///end of the first serial number being processed, do again n times (number of categry.count
times)
}
So you have a case where a CategoryID can have many SerialNumbers associated with it, Example:所以你有一个 CategoryID 可以有许多与之关联的 SerialNumbers 的情况,示例:
CategoryID SerialNumber
12345 0123445
12345 2345678
12345 0987654
12345 8756478
.... ......(n times)
I want to loop through and get each of those serial number and save to the variable, 'getDifferentSerialNumberforEachLoop' process that separately and do it again for all serial numbers associated with that CategoryID.我想遍历并获取这些序列号中的每一个并保存到变量“getDifferentSerialNumberforEachLoop”中,分别处理并再次为与该 CategoryID 关联的所有序列号执行此操作。 But at the moment I'm only getting the first SerialNumber say 0123445 of course this is because I'm using 'FirstOrDefault()' so even though the Select(i=>i.SerialNumber) value changes each time it loops through category.count the variable, getDifferentSerialNumberforEachLoop will always be the firstordefault value.
但目前我只得到第一个 SerialNumber 说 0123445 当然这是因为我正在使用 'FirstOrDefault()' 所以即使 Select(i=>i.SerialNumber) 值每次循环通过类别时都会改变。计数变量,getDifferentSerialNumberforEachLoop 将始终是第一个或默认值。
My question is: how do I make the getDifferentSerialNumberforEachLoop
to always have the next SerialNumber
value?我的问题是:如何使
getDifferentSerialNumberforEachLoop
始终具有下一个SerialNumber
值?
I can't use .Take(4)
because I don't know if category.count
will always be 4 - if that make sense?我不能使用
.Take(4)
因为我不知道category.count
是否总是 4 - 如果这有意义?
Can't use LastOrDefault
because I wouldn't get the first to the last values, I can't use List()
because I only want one SerialNumber
value at a time.不能使用
LastOrDefault
因为我不会得到第一个到最后一个值,我不能使用List()
因为我一次只想要一个SerialNumber
值。
So is there a way I could go about this?那么有什么办法可以让我 go 解决这个问题吗? I've also seen Takewhile but not sure about that?
我也看过 Takewhile 但不确定? Any other query I could use for this please?
我可以使用任何其他查询吗? Thank you.
谢谢。
I'd Suggest something like the below.我建议像下面这样的东西。
foreach(var i in category.count)
{
var getDifferentSerialNumberforEachLoop = _db.Category.Where(a => a.CategoryID ==
categoryID).Select(i=>i.SerialNumber).ToList().ForEach(serialNo => {
Console.WriteLine(serialNo);
});
}
You say you "cannot use List because you need one Serial Number at a time" but doing ToList()
and ForEach
will allow you to iterate over each Serial Number at a time.你说你“不能使用 List 因为你一次需要一个序列号”但是做
ToList()
和ForEach
将允许你一次迭代每个序列号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.