如何向现有IQueryable添加多个选择

时间:2017-09-13 17:59:01

标签: c# linq

我有一种情况,结果集在3种不同的情况下是95%相同。 5%的差异取决于给定的变量,因此填写(或不填写)剩余的5%的字段。

作为一个简单的例子,这里是返回的结果对象:

public class MyResults {
  public string PropertyA { get; set; }
  public string PropertyB { get; set; }
  public string PropertyC { get; set; }
  public string PropertyD { get; set; }
  public string PropertyE { get; set; }
}

目前我有一个方法可以构建我拥有以下内容的结果:

public List<MyResults> GetMyResults(int someParameter) {
  IQueryable<MyResults> query;

  if (someParameter == "A") {
    query = entities.Select(x => new MyResults {
      PropertyA = x.PropertyA, // Common
      PropertyB = x.PropertyB, // Common
      PropertyC = x.PropertyC, // Different
    };
  } else if (someParameter == "B") {
    query = entities.Select(x => new MyResults {
      PropertyA = x.PropertyA, // Common
      PropertyB = x.PropertyB, // Common
      PropertyD = x.PropertyD, // Different
    };
  } else {
    query = entities.Select(x => new MyResults {
      PropertyA = x.PropertyA, // Common
      PropertyB = x.PropertyB, // Common
      PropertyE = x.PropertyE, // Different
    };
  }

  return query.ToList();
}

这是所需的方式:

public List<MyResults> GetMyResults(int someParameter) {
  IQueryable<MyResults> query = entities.Select(x => new MyResults {
    PropertyA = x.PropertyA, // Common
    PropertyB = x.PropertyB, // Common
    PropertyC = x.PropertyC, // Common
  };

  if (someParameter == "A") {
    query = entities.Select(x => new MyResults {
      PropertyC = x.PropertyC // Different
    });
  } else if (someParameter == "B") {
    query = entities.Select(x => new MyResults {
      PropertyD = x.PropertyD // Different
    });
  } else {
    query = entities.Select(x => new MyResults {
      PropertyE = x.PropertyE // Different
    });
  }

  return query.ToList();
}

这样,所有结果的一致字段都是相同的,我只需要添加不同的字段。

这可能吗?

1 个答案:

答案 0 :(得分:3)

您可以按如下方式使用三元运算符:

return entities.Select(x => new MyResults {
    PropertyA = x.PropertyA, // Common
    PropertyB = x.PropertyB, // Common
    PropertyC = someParameter == 1 ? x.PropertyC : null,
    PropertyD = someParameter == 2 ? x.PropertyD : null,
    PropertyE = someParameter == 3 ? x.PropertyE : null,
}).ToList();

基本上string的默认值为null,如果someParameter与给定propertyX的情况不匹配,则属性值为{{1} }。如果是,它将获得所需的值