Linq动态选择?

时间:2013-01-14 13:28:47

标签: c# linq

我有以下代码将表转换为其数据透视。

IQueryable<MeterReadingsForChart> meterReadings = MeterReadingManager.GetCustomerMeterReadings(customer.sno, MeterType, Meter, startDate, endDate, DateTimeManager.GetTimeIntervalTypeById(DateRangeType)).AsQueryable();

// meterReadings Output:
// Customer  Value ReadingTypes
// cust1       235           T1
// cust1       241           T2
// cust1       765           T3
// cust1       247           T4
// cust1       967        Total
// ..........

var table = MeterReadingManager.GetMeterReadingsPivot(meterReadings, MeterType);

// table Output (pivot of meterReadings):
// Customer     T1     T2    T3    T4    Total
// cust1       235    241   765   247      967
// ............

我有一个ReadingTypes字符串数组:

string[] selectedValues = Parameters.Split(','); 
// For example output : { "T1", "Total" }

我想动态获取数据透视列。使用上面的数组。我期望的数据透视表:

// filtered pivot from meterReadings pivot Output:
// Customer     T1    Total
// cust1       235      967
// ............

我该怎么做?动态选择还是其他方式?

转换功能也是:

return (from m in meterReadings
        group m by new { date = m.ReadDate } into g
        select new
        {
           ReadDate = g.Key.date.ToString("dd.MM.yyyy - HH:mm:ss"),
           T1 = (from t1 in g
                where t1.Name == "T1"
                select t1.Value.ToString("0.00 " + t1.Unit + "")).FirstOrDefault(),
           T2 = (from t2 in g
                where t2.Name == "T2"
                select t2.Value.ToString("0.00 " + t2.Unit + "")).FirstOrDefault(),
           T3 = (from t3 in g
                where t3.Name == "T3"
                select t3.Value.ToString("0.00 " + t3.Unit + "")).FirstOrDefault(),
           Total_T1 = (from t1 in g
                      where t1.Name == "Toplam T1"
                      select t1.Value.ToString("0.00 " + t1.Unit + "")).FirstOrDefault(),
           Total_T2 = (from t1 in g
                       where t1.Name == "Toplam T2"
                       select t1.Value.ToString("0.00 " + t1.Unit + "")).FirstOrDefault(),
           Total_T3 = (from t1 in g
                      where t1.Name == "Toplam T3"
                      select t1.Value.ToString("0.00 " + t1.Unit + "")).FirstOrDefault(),
           Reactive = (from t1 in g
                      where t1.Name == "Reaktif"
                      select t1.Value.ToString("0.00 " + t1.Unit + "")).FirstOrDefault(),
           Capasitive = (from t2 in g
                        where t2.Name == "Kapasitif"
                        select t2.Value.ToString("0.00 " + t2.Unit + "")).FirstOrDefault()
           }).AsQueryable<object>();

...谢谢

1 个答案:

答案 0 :(得分:0)

我解决了它:

var table = MeterReadingManager.GetMeterReadingsPivot(meterReadings, MeterType).Select("new (" + Parameters + ")");