能够有条件地选择要 select 的行

Ability to conditionally choose what row to select

这主要是为了看看我是否可以找到解决此限制的方法。

假设我有以下查询:

var query = (from a in db.Table
             where a.CustomFieldId == FieldID && a.ListingId == listingID
             select a.SomeTypeValue);

我正在查询的 table 是为可能类型不同的自定义字段设置的,因此它有多个列,但仅使用适当的列来存储基于字段的 selected 的值类型。

table 看起来有点像这样:

我希望能够在不重写整个查询的情况下选择我 select 的列。这可能吗?

提前致谢,

您的查询可以改写为使用 "Method Call LINQ":

db.Table
  .Where(a => a.CustomFieldId == FieldID && a.ListingId == listingID)
  .Select(x => x.SomeType);

您可以将查询拆分为 Where 和 Select 部分,然后:

var result = whereQuery.Select(x => x.BoolValue);

var result = whereQuery.Select(x => x.IntValue);

您甚至可以将该逻辑封装到方法中:

IEnumerable<T> GetValues<T>() {
  var query = db.Table
      .Where(a => a.CustomFieldId == FieldID && a.ListingId == listingID);

  if (typeof(T)==typeof(bool)) {
    return query.Select(x => x.BoolColumn);
  }
  else if (typeof(T) == typeof(int)) {
    return query.Select(x => x.IntColumn);
  }
  // other types here
}