在 LINQ 选择中使用公式

我有一个如下所示的数据表:


Row Side    Value

1   A       34.8

1   B       33.9

1   C       33.1

2   A       32.6

2   B       32.0

2   C       35.7

3   A       34.6

3   B       34.0

3   C       33.5

我需要做的一件事是计算我喜欢的每一行的平均值:


var avg = (from row in dt.AsEnumerable()

          group row by new { RowMeas = row.Field<string>("Row") } into grp

          select new

          {

             RowMeas = grp.Key.RowMeas,

             AVG = grp.Average(r => r.Field<double>("Value"))

         }).ToList();

现在我需要做一些类似的事情,但不是只取平均值,我想为每一行使用一个公式,比如 4*A + 3*B + 2*C


我可以像上面那样使用 LINQ 来做到这一点,而不是 AVG 以某种方式使用这个公式吗?在其他软件中,我们通过转置数据表手动执行此计算,以便有 A、B、C 列,然后可以在新列的公式中使用这些列。由于在 C# 中转置不是一种简单的方法,我希望我可以使用 LINQ 来做到这一点。


GCT1015
浏览 197回答 1
1回答

慕侠2389804

var dt = new DataTable();dt.Columns.Add("Row", typeof(string));dt.Columns.Add("Side", typeof(string));dt.Columns.Add("Value", typeof(double));dt.Rows.Add(1, "A", 34.8);dt.Rows.Add(1, "B", 33.9);dt.Rows.Add(1, "C", 33.1);dt.Rows.Add(2, "A", 32.6);dt.Rows.Add(2, "B", 32.0);dt.Rows.Add(2, "C", 35.7);dt.Rows.Add(3, "A", 34.6);dt.Rows.Add(3, "B", 34.0);dt.Rows.Add(3, "C", 33.5);var query = dt&nbsp; &nbsp; .AsEnumerable()&nbsp; &nbsp; .GroupBy(x => x.Field<string>("Row"))&nbsp; &nbsp; .Select(x => new&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Row = x.Key,&nbsp; &nbsp; &nbsp; &nbsp; A = x.Where(y => y.Field<string>("Side") == "A").Select(z => z.Field<double>("Value")).FirstOrDefault(),&nbsp; &nbsp; &nbsp; &nbsp; B = x.Where(y => y.Field<string>("Side") == "B").Select(z => z.Field<double>("Value")).FirstOrDefault(),&nbsp; &nbsp; &nbsp; &nbsp; C = x.Where(y => y.Field<string>("Side") == "C").Select(z => z.Field<double>("Value")).FirstOrDefault()&nbsp; &nbsp; })&nbsp; &nbsp; .Select(x => new&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Row = x.Row,&nbsp; &nbsp; &nbsp; &nbsp; Result = 4 * x.A + 3 * x.B + 2 * x.C&nbsp; &nbsp; })&nbsp; &nbsp; ;foreach (var q in query)&nbsp; &nbsp; Console.WriteLine("Row = {0}, Result = {1}", q.Row, q.Result);结果在 LinqPad 中。
打开App,查看更多内容
随时随地看视频慕课网APP