如何使用此示例在Linq中动态调整

时间:2011-08-03 18:38:22

标签: c# linq

下面的问题出现在代码中,即说出DY1 =,DY2 =等的位。我不知道会有多少,所以我需要动态地进行。

这是我的文本文件:

Product, Origin Year, Development Year, Incremental Value
Comp, 1992, 1992, 110.0
Comp, 1992, 1993, 170.0
Comp, 1993, 1993, 200.0
Non-Comp, 1990, 1990, 45.2
Non-Comp, 1990, 1991, 64.8
Non-Comp, 1990, 1993, 37.0
Non-Comp, 1991, 1991, 50.0
Non-Comp, 1991, 1992, 75.0
Non-Comp, 1991, 1993, 25.0
Non-Comp, 1992, 1992, 55.0
Non-Comp, 1992, 1993, 85.0
Non-Comp, 1993, 1993, 100.0

这是我的代码(从LinqPad粘贴):

void Main()
{
  using (var reader = new StreamReader("C:\\temp\\ExampleData.txt"))
  {
    var products =
        (from line in reader.Lines()
        where !line.StartsWith("Product")
        let parts = line.Split(',')
        select new {Product=parts[0], Origin_Year=parts[1], Development_Year=parts[2], Incremental_Value=parts[3], DY=int.Parse(parts[2]) - int.Parse(parts[1]) + 1 }).ToList();
    products.Dump();

    var grps = from p in products
    group p by new {p.Product, p.Origin_Year}
    into g
    select (new { g.Key.Product, g.Key.Origin_Year, 

    DY1 = g.Where(c => c.DY == 1).Select (c => c.Incremental_Value).FirstOrDefault(),
    DY2 = g.Where(c => c.DY == 2).Select (c => c.Incremental_Value).FirstOrDefault(),
    DY3 = g.Where(c => c.DY == 3).Select (c => c.Incremental_Value).FirstOrDefault(),
    DY4 = g.Where(c => c.DY == 4).Select (c => c.Incremental_Value).FirstOrDefault()    
    });

    grps.Dump();
  }
}

}// Temporary hack to enable extension methods

/// <summary>
/// Operators for LINQ to Text Files
/// </summary>
public static class Extensions
{
  public static IEnumerable<String> Lines(this TextReader source)
  {
    String line;

    if (source == null)
      throw new ArgumentNullException("source");

    while ((line = source.ReadLine()) != null)
      yield return line;
  }

这是我的输出:

Product   Origin_Year  DY1    DY2    DY3   DY4 
Comp      1992         110.0  170.0  null  null  
Comp      1993         200.0  null   null  null  
Non-Comp  1990         45.2   64.8   null  37.0  
Non-Comp  1991         50.0   75.0   25.0  null  
Non-Comp  1992         55.0   85.0   null  null  
Non-Comp  1993         100.0  null   null  null 

1 个答案:

答案 0 :(得分:2)

我能提供的最佳建议是为每个可能的DY返回一组值。

首先将Incremental_Value查询中的products字段修改为double(即double.Parse(parts[3]))。

现在为最大数量的DY创建一个可枚举:

    var dys = Enumerable.Range(1, products.Max(p => p.DY));

然后grps查询如下所示:

    var grps =
        from p in products
        group p by new
        {
            p.Product,
            p.Origin_Year,
        } into g
        let lookup = g.ToLookup(x => x.DY, x => x.Incremental_Value)
        select new
        {
            g.Key.Product,
            g.Key.Origin_Year, 
            DYs = dys.Select(x => lookup[x].Sum()).ToArray(),
        };

这对你有用吗?