简体   繁体   English

数据表LINQ Join C#

[英]DataTable LINQ Join C#

I have the following tables (DataTable): 我有以下表格(DataTable):

CallData table has fields Strike , MidPrice and PutData table with fields Strike and Midprice I would like to join them on Strike and choose minimum of the following expression: CallData表具有StrikeMidPricePutData表以及StrikeMidprice字段,我想将它们加入Strike并选择以下表达式的最小值:

Abs(CallData.MidPrice - PutData.MidPrice)

Here is how I image it should look in LINQ terms: 这是我用LINQ术语显示的图像:

var result = (from CallRow in CallData.AsEnumerable()
              join PutRow in PutData.AsEnumerable()
                on CallRow.Field<int>("Strike") equals PutRow.Field<int>("Strike") 
            select new { Abs(CallRow.Field<double>("MidPrice")
                             - PutRow.Field<double>("MidPrice"))
                       }).Min();

However, expression 但是,表达

 Abs(CallRow.Field<double>("MidPrice")  

is underlined by wavy line and the message says: 由波浪线强调,并且消息显示:

Invalid anonymous type member declared. 声明了无效的匿名类型成员。 Anonymous type member must be declared with a member assignment simple name or member access. 必须使用成员分配简单名称或成员访问权限来声明匿名类型成员。

Any ideas how to correct it? 任何想法如何纠正它?

EDIT: Great answer Selman22! 编辑:很好的答案Selman22! I have found the following example in link 我在链接中找到以下示例

static void GetNameAndDescription {ProductInfo[] products}
{
Console.WriteLine("Names and Descriptions:")
var nameDesc = from p in product select new {p.Name, p.Description};
}

Do you know why this code is valid with 'new' 您知道为什么此代码对'new'有效吗

You don't even need an anonymous type here. 您甚至不需要在这里使用匿名类型。 Just remove the new part 只需删除new零件

var result = (from CallRow in CallData.AsEnumerable()
          join PutRow in PutData.AsEnumerable()
          on CallRow.Field<int>("Strike") equals PutRow.Field<int>("Strike") 
          select Abs(CallRow.Field<double>("MidPrice") 
                    - PutRow.Field<double>("MidPrice"))).Min();

The error message explains the reason clearly: 错误消息清楚地说明了原因:

Anonymous type member must be declared with a member assignment simple name or member access. 必须使用成员分配简单名称或成员访问权限来声明匿名类型成员。

In this case you have a complex expression, so you need to set the value to a property to make it work. 在这种情况下,您有一个复杂的表达式,因此您需要将值设置为属性以使其起作用。 like new { value = Abs(...) } , but as I said already you don't need it... 就像new { value = Abs(...) } ,但是正如我已经说过的,您不需要它...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM