任何人都可以帮我写一个linq查询,它有点混乱......基本上我有一个变量,我的代码中的numeberOfDays,本例为8
我有一张表列出了这一点。
DayFrom DayTo Price
1 3 20
4 5 30
6 8 40
8 25 150
在我的情况下,我需要每天从linq返回一行8 ...
因此我最终得到了
20 (because day 1 and its from 1 to 3)
20 (because day 2 and its from 1 to 3)
20 (because day 3 and its from 1 to 3)
30 (because day 4 and its from 4 to 5)
30 (because day 5 and its from 4 to 5)
40 (because day 6 and its from 6 to 8)
40 (because day 6 and its from 6 to 8)
40 (because day 7 and its from 6 to 8)
40 (because day 8 and its from 6 to 8)
// no more records will be listed because we are on 8 and its the last day..
所以基本上我只需要在这种情况下返回一个TOTAL
20 + 20 + 20 + 30 + 30 + 40 + 40 + 40 + 40 = 280 .....
我不知道从哪里开始,如果它是在代码中,那么我可以使用一个计数器为numOfDays和一个for Next来检查Dayfrom和Dayto内的日期和价格..
我真的很感激任何反馈..
由于
答案 0 :(得分:1)
var priceList = new[] {
new {DayFrom = 1, DayTo = 3, PriceList = 20},
new {DayFrom = 4, DayTo = 5, PriceList = 30},
new {DayFrom = 6, DayTo = 8, PriceList = 40},
new {DayFrom = 9, DayTo = 25, PriceList = 150}
};
int days = 8;
var total = (from p in priceList
from d in Enumerable.Range(1, days)
where p.DayFrom <= d && p.DayTo >= d
select p.PriceList).Sum();
Console.WriteLine(total);
但是在DayTo和DayFrom中你的数据有点奇怪,所以我把它改成了9。
答案 1 :(得分:1)
假设您有一个名为DataItem
的类,其属性为DayFrom
,DayTo
和Price
,则以下内容应该有效(请注意,我还没有对其进行过测试):
int Total(int numberOfDays, DataItem[] items){
var query =
from item in items
let daysInData = Math.Min(item.DayTo, numberOfDays) - item.DayFrom + 1
where item.DayFrom >= numberOfDays
select item.Price * daysInData;
return query.Sum();
}
答案 2 :(得分:0)
int numberOfDays = 8;
var data = new[] { new {DayFrom = 1, DayTo = 3, Price = 20},
new {DayFrom = 4, DayTo = 5, Price = 30},
new {DayFrom = 6, DayTo = 8, Price = 40},
new {DayFrom = 8, DayTo = 25, Price = 150}};
int sum = data.SelectMany(x => Enumerable.Repeat(x, x.DayTo - x.DayFrom + 1))
.Select(x => x.Price)
.Take(numberOfDays)
.Sum();
Console.WriteLine(sum);