【问题标题】:How to check if column is exist in Linq join query c#?如何检查Linq join query c#中是否存在列?
【发布时间】:2014-01-25 07:15:50
【问题描述】:

您好,我正在运行一个 Linq 查询来连接三个表。下面是查询...

answerText = ds.Tables[0];
questionAvg = ds.Tables[1];
interviews = ds.Tables[2];

var data = from at in answerText.AsEnumerable()
           join qa in questionAvg.AsEnumerable() on at.Field<int>("ID") equals qa.Field<int>("DealerID")
           join inter in interviews.AsEnumerable() on at.Field<int>("ID") equals inter.Field<int>("DealerID")
           select new
           {
               DealerID = at.Field<int>("ID"),
               DealerName = at.Field<string>("Name"),
               AnswerText1 = at.Field<int?>("12"),                           
               AnswerText2 = at.Field<int?>("8"),
               AnswerText3 = at.Field<int?>("4"),
               AnswerText4 = at.Field<int?>("0"),
               AnswerText5 = at.Field<int?>("-4"),
               Rank = qa.Field<Int64?>("Rank"),
               Average = qa.Field<decimal?>("Average"),
               N = inter.Field<int?>("N")
           };

现在有时 answerText 数据表将只有第 12 列和第 8 列..,所以它缺少第 4 0 -4 列。我应该如何避免在上面的查询中检查该列并在那里提供 0。

【问题讨论】:

  • 你有异常吗?

标签: c# linq linq-to-objects


【解决方案1】:

我不是 100% 确定您在问什么,但我认为您需要 AnswerText 属性为 int 而不是 int?。当项目不存在时,它们应该设置为0。您可以使用?? 运算符:

var data = from at in answerText.AsEnumerable()
           join qa in questionAvg.AsEnumerable() on at.Field<int>("ID") equals qa.Field<int>("DealerID")
           join inter in interviews.AsEnumerable() on at.Field<int>("ID") equals inter.Field<int>("DealerID")
           select new
           {
               DealerID = at.Field<int>("ID"),
               DealerName = at.Field<string>("Name"),
               AnswerText1 = at.Field<int?>("12") ?? 0,                           
               AnswerText2 = at.Field<int?>("8") ?? 0,
               AnswerText3 = at.Field<int?>("4") ?? 0,
               AnswerText4 = at.Field<int?>("0") ?? 0,
               AnswerText5 = at.Field<int?>("-4") ?? 0,
               Rank = qa.Field<Int64?>("Rank"),
               Average = qa.Field<decimal?>("Average"),
               N = inter.Field<int?>("N")
           };

【讨论】:

  • 我的问题是 answerText 数据表中的列存在不确定性。在某些情况下,它没有给我第 4、0、-4 列。那么如何避免呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-18
  • 2017-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多