如何在linq中实现“where”子句

时间:2013-11-22 03:02:01

标签: c# linq

可能查询需要识别id或者我应该说集合中的id组,可以查询是这样的

var logs = from record in RecordCollection(string.Concat(sourcePath + fileName))
                           where record.Id == 800 && record.Id == 307 && record.Id == 314 && record.Id == 372 && record.Id == 105
                           select record;

这是正确的方法吗?即使收集中有ID,我也没有得到任何结果。 TIA

4 个答案:

答案 0 :(得分:2)

&&替换为||

var logs = from record in RecordCollection(string.Concat(sourcePath + fileName))
           where record.Id == 800 ||
                 record.Id == 307 || 
                 record.Id == 314 || 
                 record.Id == 372 ||
                 record.Id == 105
           select record;

或者像这样短:

var ids = new []{800,307,314,372,105};
var logs = from record in RecordCollection(string.Concat(sourcePath + fileName))
           where ids.Contains(record.Id)
           select record;

答案 1 :(得分:1)

您可能需要||(OR)运算符:

var logs = from record in RecordCollection(string.Concat(sourcePath + fileName))
           where record.Id == 800 || 
                 record.Id == 307 || 
                 record.Id == 314 || 
                 record.Id == 372 || 
                 record.Id == 105
           select record;

现在您正在检查当前正在迭代其Id的一条记录是否具有值800和307以及314等等。您想检查它是否具有其中任何一条记录。

答案 2 :(得分:0)

考虑以下代码......

var logs = from record in RecordCollection(string.Concat(sourcePath + fileName))
                       where new List<int> { 800, 307, 314, 372, 105}.Contains(record.Id)
                       select record;

祝你好运!

答案 3 :(得分:0)

&&替换为||

要在很多地方使用,你应该建立一个方法。示例:

public static bool IsIn<T>(this T source, params T[] values)
{
    return values.Contains(source);
}

并称之为:

var logs = from record in RecordCollection(string.Concat(sourcePath + fileName))
                       where record.IsIn(800,105,307)
                       select record;