我是LINQ的新手,但我想知道是否可以使用LINQ从以下布局转移数据:
CustID | OrderDate | Qty 1 | 1/1/2008 | 100 2 | 1/2/2008 | 200 1 | 2/2/2008 | 350 2 | 2/28/2008 | 221 1 | 3/12/2008 | 250 2 | 3/15/2008 | 2150
进入这样的事情:
CustID | Jan- 2008 | Feb- 2008 | Mar - 2008 | 1 | 100 | 350 | 250 2 | 200 | 221 | 2150
Amy B.. 184
像这样的东西?
ListmyList = GetCustData(); var query = myList .GroupBy(c => c.CustId) .Select(g => new { CustId = g.Key, Jan = g.Where(c => c.OrderDate.Month == 1).Sum(c => c.Qty), Feb = g.Where(c => c.OrderDate.Month == 2).Sum(c => c.Qty), March = g.Where(c => c.OrderDate.Month == 3).Sum(c => c.Qty) });
GroupBy
在Linq中,它与SQL不同.在SQL中,您获得密钥和聚合(行/列形状).在Linq中,您可以获得键和任何元素作为键的子元素(层次结构形状).要进行透视,您必须将层次结构投影回您选择的行/列形式.
像这样的东西?
ListmyList = GetCustData(); var query = myList .GroupBy(c => c.CustId) .Select(g => new { CustId = g.Key, Jan = g.Where(c => c.OrderDate.Month == 1).Sum(c => c.Qty), Feb = g.Where(c => c.OrderDate.Month == 2).Sum(c => c.Qty), March = g.Where(c => c.OrderDate.Month == 3).Sum(c => c.Qty) });
GroupBy
在Linq中,它与SQL不同.在SQL中,您获得密钥和聚合(行/列形状).在Linq中,您可以获得键和任何元素作为键的子元素(层次结构形状).要进行透视,您必须将层次结构投影回您选择的行/列形式.
我使用linq扩展方法回答了类似的问题:
// order s(ource) by OrderDate to have proper column ordering var r = s.Pivot3(e => e.custID, e => e.OrderDate.ToString("MMM-yyyy") , lst => lst.Sum(e => e.Qty)); // order r(esult) by CustID
(+)通用实现
( - )绝对比David B慢
任何人都可以改进我的实现(即方法执行列和行的排序)?
我认为,最好的方法是使用查找:
var query = from c in myList group c by c.CustId into gcs let lookup = gcs.ToLookup(y => y.OrderDate.Month, y => y.Qty) select new { CustId = gcs.Key, Jan = lookup[1].Sum(), Feb = lookup[2].Sum(), Mar = lookup[3].Sum(), };