代码之家  ›  专栏  ›  技术社区  ›  Retrocoder

Linq-GroupBy问题

  •  1
  • Retrocoder  · 技术社区  · 14 年前

    我需要对列表中的数据进行分组,但不能对groupBy子句进行硬编码,因为它必须由用户定义。

    List<ThirdPartyExportTransaction> transactions = new List<ThirdPartyExportTransaction>();
    transactions.Add(new ThirdPartyExportTransaction { DeviceId = "TEST01-1", Unit = 1 });
    transactions.Add(new ThirdPartyExportTransaction { DeviceId = "TEST01-2", Unit = 2 });
    transactions.Add(new ThirdPartyExportTransaction { DeviceId = "TEST01-2", Unit = 3 });
    transactions.Add(new ThirdPartyExportTransaction { DeviceId = "TEST01-1", Unit = 4 });
    transactions.Add(new ThirdPartyExportTransaction { DeviceId = "TEST01-1", Unit = 5 });
    transactions.Add(new ThirdPartyExportTransaction { DeviceId = "TEST01-2", Unit = 6 });
    
    
    var s= transactions.GroupBy(r => extractText(r.DeviceId, "TEST01-.")); // Need to change this
    
    // At this point s now holds the grouped list
    
    private static string extractText(string fieldText, string regExp)
    {
       Match m = Regex.Match(fieldText, regExp);
    
       return m.Success ? m.Value : "";
    } 
    
    2 回复  |  直到 14 年前
        1
  •  1
  •   Jerome    14 年前

    反思?

    r => extractText(r.GetType().GetProperty("DeviceId").GetValue(r, null), "TEST01-.")