C#Linq组具有唯一值的行

时间:2017-08-08 15:08:57

标签: c# linq

给定具有以下行的数据表。

files=()
while IFS= read -r -d '' filename; do
  files+=( "$filename" )
done < <(find /folder/where/the/files/are/ -name '*.xml' -print0)

idx=0
while ((idx=0; idx<${#files[@]}; idx+=256)); do
  ./myProgram "${files[@]:$idx:256}"
done

预期结果:

POLICY START_DT     END_DT        AMOUNT  TYPE

1000   08/01/2017   09/01/2017   -10.00   A
1000   08/01/2017   09/01/2017    30.00   C

我希望始终采用第一个TYPE值并应用于分组行

到目前为止我所拥有的:

POLICY START_DT      END_DT       AMOUNT  TYPE

1000   08/01/2017    09/01/2017   20.00   A

2 个答案:

答案 0 :(得分:1)

您不能将TYPE用作分组标准。因此,请将其从您的无组织分组类型中删除。

要获取第一行的TYPE值,您可以稍后从groupings的第一个条目中读取该值:

var results = from row in dt.AsEnumerable()
              group row by new
              {
                 Policy = row.Field<int>("POLICY"),
                 StartDt = row.Field<string>("START_DT"),
                 EndDt = row.Field<string>("END_DT")
              } into groupings
              select new
              {
                 groupings.Key.Policy,
                 groupings.Key.StartDt,
                 groupings.Key.EndDt,
                 groupings.First().Field<string>("TYPE"),
                 TotalAmount = groupings.Sum(t => t.Fields<decimal>("AMOUNT"))
              }

但我必须承认,我不确定这是否始终采用第一行的TYPE 值,无论如何,我不确定GroupBy是否保持元素的顺序。

答案 1 :(得分:1)

不要在分组中包含类型

var results = from row in dt.AsEnumerable()
          group row by new
          {
             Policy = row.Field<int>("POLICY"),
             StartDt = row.Field<string>("START_DT"),
             EndDt = row.Field<string>("END_DT"),                 
          } into groupings
          select new
          {
             Policy = groupings.Key.Policy,
             StartDt = groupings.Key.StartDt,
             EndDt = groupings.Key.EndDt,
             Type = groupings.OrderBy(r => r.Field<string>("TYPE")).First().Field<string>("TYPE"),
             Amount = groupings.Sum(t => t.Fields<decimal>("AMOUNT"))
          };