有人可以用linq查询帮助我获得以下结果集吗?
首先是DInfo
ID DId DName
1 D1 DName1
2 D2 DName2
3 D3 Dname3
第二个是MInfo
ID DId MId MName
1 D1 1 MName1
2 D1 2 MName2
3 D2 1 MName3
4 D2 2 MName4
5 D2 3 MName5
第三是VData(交易表)
ID Did Mid Value DateTime
1 D1 1 10.25 2018-04-15 17:33:22
2 D1 1 11.26 2018-04-15 19:33:22
3 D1 1 12.30 2018-04-15 22:33:22
4 D1 2 45.50 2018-04-15 17:33:22
5 D1 2 50.40 2018-04-15 19:33:22
6 D1 2 60.66 2018-04-15 22:33:22
6 D2 1 60.41 2018-04-15 19:33:22
7 D2 1 66.22 2018-04-15 22:33:22
8 D2 1 70.65 2018-04-15 23:33:22
我对结果集的想法是从DInfo获取所有不同的行,并从MInfo查找与DInfo的DID匹配的所有行,然后为每个唯一行从事务表中获取第一个和最后一个值(基于日期时间)
我期望的ResultSet如下
MName OpeningValue ClosingValue
MName1 10.25 12.30
MName2 45.50 60.66
MName3 60.41 70.65
以上数据仅供参考,实际上在生产场景中可能会有所不同。所有表中的行数。
谢谢
答案 0 :(得分:0)
尝试关注:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication108
{
class Program
{
static void Main(string[] args)
{
DataTable mInfo = new DataTable();
mInfo.Columns.Add("ID", typeof(int));
mInfo.Columns.Add("Did", typeof(string));
mInfo.Columns.Add("Mid", typeof(int));
mInfo.Columns.Add("MName", typeof(string));
mInfo.Rows.Add(new object[] {1, "D1", 1, "MName1"});
mInfo.Rows.Add(new object[] {2, "D1", 2, "MName2"});
mInfo.Rows.Add(new object[] {3, "D2", 1, "MName3"});
mInfo.Rows.Add(new object[] {4, "D2", 2, "MName4"});
mInfo.Rows.Add(new object[] {5, "D2", 3, "MName5"});
DataTable vData = new DataTable();
vData.Columns.Add("ID", typeof(int));
vData.Columns.Add("Did", typeof(string));
vData.Columns.Add("Mid", typeof(int));
vData.Columns.Add("Value", typeof(decimal));
vData.Columns.Add("DateTime", typeof(DateTime));
vData.Rows.Add(new object[] { 1, "D1", 1, 10.25, DateTime.Parse("2018-04-15 17:33:22")});
vData.Rows.Add(new object[] { 2, "D1", 2, 11.26, DateTime.Parse("2018-04-15 19:33:22")});
vData.Rows.Add(new object[] { 3, "D2", 1, 12.30, DateTime.Parse("2018-04-15 22:33:22")});
vData.Rows.Add(new object[] { 4, "D2", 2, 45.50, DateTime.Parse("2018-04-15 17:33:22")});
vData.Rows.Add(new object[] { 5, "D2", 3, 50.40, DateTime.Parse("2018-04-15 19:33:22")});
vData.Rows.Add(new object[] { 6, "D1", 2, 60.66, DateTime.Parse("2018-04-15 22:33:22")});
vData.Rows.Add(new object[] { 6, "D2", 1, 60.41, DateTime.Parse("2018-04-15 19:33:22")});
vData.Rows.Add(new object[] { 7, "D2", 1, 66.22, DateTime.Parse("2018-04-15 22:33:22")});
vData.Rows.Add(new object[] { 8, "D2", 1, 70.65, DateTime.Parse("2018-04-15 23:33:22")});
var results = vData.AsEnumerable().OrderBy(x => x.Field<DateTime>("DateTime"))
.GroupBy(x => new { Did = x.Field<string>("Did"), Mid = x.Field<int>("Mid") })
.Select(x => new
{
MName = mInfo.AsEnumerable().Where(y => (y.Field<string>("Did") == x.Key.Did) && (y.Field<int>("Mid") == x.Key.Mid)).FirstOrDefault().Field<string>("MName"),
OpeningValue = x.First().Field<decimal>("Value"),
ClosingValue = x.Last().Field<decimal>("Value")
}).ToList();
}
}
}