Any .Net function or linq query to unpivot data

我的梦境 提交于 2019-12-21 18:32:39

问题


Is there any .net library available to unpivot excel data? I am currently using LinqToExcel framework to read data from spreadsheets, so not sure if there are dynamic linq queries available to perform the unpivot. Thanks for any suggestions. BTW, I am looking for a solution which could handle multiple columns.

Example Original Table

Product Location  Customer1   Customer2   Customer3
  A        X          10         20         100

Destinaton Table

Product Location Customer    Demand
  A        X      Customer1    10
  A        X      Customer2    20
  A        X      Customer3    100

回答1:


Try something like this:

var customer1 =
    from c in excel.Worksheet()
    select new
    {
        Product = c["Product"],
        Location = c["Location"],
        Customer = "Customer1",
        Demand = c["Customer1"],
    };

var customer2 =
    from c in excel.Worksheet()
    select new
    {
        Product = c["Product"],
        Location = c["Location"],
        Customer = "Customer2",
        Demand = c["Customer2"],
    };

var customer3 =
    from c in excel.Worksheet()
    select new
    {
        Product = c["Product"],
        Location = c["Location"],
        Customer = "Customer3",
        Demand = c["Customer3"],
    };

var customers = customer1.Union(customer2).Union(customer3);

Based on your comment try this:

var columns = 4; /* how many columns to unpivot */
var customers =
    from n in Enumerable.Range(2, columns)
    from c in excel.Worksheet()
    select new
    {
        Product = c["Product"].Value,
        Location = c["Location"].Value,
        Column = n.ToString(),
        Demand = c[n].Value,
    };


来源:https://stackoverflow.com/questions/11639687/any-net-function-or-linq-query-to-unpivot-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!