Linq中的分组范围

时间:2014-09-03 11:33:25

标签: c# linq group-by

谢谢大家,很抱歉,我很初学。让我详细解释一下:我有一张桌子" theTable"并有两列"日期"在DateTime和" Value"在双。 我想要的结果是:1。检查哪个日期是最小的2.将此作为firstdat

我已经尝试但似乎无法正常工作

from cf in theTable.
group t by  t.Month.Month / 8 + t.Month.Year into g 

select new { sum = g.Sum(x=>x.Amount) ,year = g.Key}

3 个答案:

答案 0 :(得分:0)

您可以尝试做类似的事情:

    private static void Main(string[] args)
    {
        var columns = new List<Column>();

        var dateRanges = new List<DateRange>()
        {
            new DateRange(new DateTime(2013, 09, 03), new DateTime(2014, 09, 03))
        };

        var result = columns.GroupBy(
            column => dateRanges.FirstOrDefault(dr => dr.IsInRange(column.Date)),
            (dr, drc) => new KeyValuePair<DateRange, int>(dr, drc.Sum(v => v.Value)));
    }

    public struct DateRange
    {
        public DateRange(DateTime from, DateTime to)
            : this()
        {
            From = from;
            To = to;
        }

        public bool IsInRange(DateTime date)
        {
            return date >= From && date <= To;
        }

        public DateTime From { get; private set; }
        public DateTime To { get; private set; }
    }

    public class Column
    {
        public int Value { get; set; }
        public DateTime Date { get; set; }
    }

答案 1 :(得分:0)

theTable.GroupBy(t => t.Date.Month / 8 + t.Date.Year)
.Select(g => g.Sum(x = > x.Value));

例如,如果你采用8 / 1991-7 / 1992的范围,他们将最终进入同一组:

8/8 + 1991 = 7/8 + 1992 = 1992

答案 2 :(得分:-1)

myList.Where(x=> x.Date < lastDate && x.Date > firstDate).Sum(x=>x.Value)

不确定答案,因为问题不是很清楚,但这是所有财产的总和&#34;价值&#34;列表中的哪个属性&#34;日期&#34;介于日期firstDate和DateDate之间。