带有字符串数组的Concatenated Where子句

时间:2012-10-08 21:37:33

标签: c# asp.net-mvc asp.net-mvc-3 entity-framework linq-to-entities

我想知道是否有办法使用int数组创建连接的WHERE子句。我需要得到整个数组的结果。我可以这样做:

public ViewResult Results(int? programId, int? programYear, int? programTypeId, string toDate, string fromDate, int?[] programTypeIdList, int?[] programIdList)
{
    surveyResponseRepository.Get().Any(x => x.ProgramId == programIdList);
}

2 个答案:

答案 0 :(得分:4)

使用Contains

surveyResponseRepository.Get().Any(x => programIdList.Contains(x.ProgramId));

虽然这会告诉您任何结果是否符合该标准。

我怀疑你想使用Where代替Any

surveyResponseRepository.Get().Where(x => programIdList.Contains(x.ProgramId));

另外,为什么使用可以为空的int数组呢?如果您尝试使参数可选,只需将其保留为常规int的数组并检查null:

public ViewResult Results(int? programId, int? programYear, int? programTypeId, string toDate, string fromDate, int[] programTypeIdList, int[] programIdList)
{
    return surveyResponseRepository.Get()
        .Where(x => programIdList == NULL 
                    || programIdList.Contains(x.ProgramId));

}

答案 1 :(得分:1)

你可以这样做:

public ViewResult Results(int? programId, int? programYear, int? programTypeId, string toDate, string fromDate, int?[] programTypeIdList, int?[] programIdList) 
{
     surveyResponseRepository.Get().Where(x => programIdList.HasValue && programIdList.Value.Contains(x.ProgramId)); 
}