KG Sosa
KG Sosa

Reputation: 70

How to implement "where" clause in linq

May query needs to identify id or I should say group of ids in a collection, may query is like this

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;

is this the right way? I'm not getting any result even if there are ids in the collection. TIA

Upvotes: 0

Views: 463

Answers (4)

Le Vu
Le Vu

Reputation: 437

Replace && with ||.

For use in many place you should build a method. Example here :

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

and call it :

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

Upvotes: 0

gpmurthy
gpmurthy

Reputation: 2427

Consider the following Code...

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

Good Luck!

Upvotes: 0

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44438

You probably want the || (OR) operator:

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;

Right now you're checking if the one record you're currently iterating its Id has the value 800 and 307 and 314 and etc. You want to check if it has any of those.

Upvotes: 1

King King
King King

Reputation: 63387

Replace && with ||

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;

Or shorter like this:

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;

Upvotes: 2

Related Questions