gofor.net
gofor.net

Reputation: 4298

how to use IN operator in LINQ

I have the list of ProjectId like 14,15,18 and i want to search those items from my datatable using linq.

now i have created the query like

IEnumerable<DataRow> drProjList = from a in dtProj.AsEnumerable()
                                  where a.Field<int>("ProjectId")
                                        .ToString()
                                        .Contains(projFilter)
                                   select a;

but i am not getting the 0 elements.

can any body suggest me any other way like IN operator in linq.

thanks in advance

EDIT projFilter is the pure string which have the 14,15,18,... project ids.

Upvotes: 2

Views: 3118

Answers (5)

Fnop
Fnop

Reputation: 225

You need to parse the project filter into collection of integers first.

var projectIds = projFilter.Split(',').Select(x => Convert.ToInt32(x)).ToList();

var drProjList =
    from a in dtProj.AsEnumerable()
    where projectIds.Contains(a.ProjectId)
    select a;

Upvotes: 1

Jason Ridge
Jason Ridge

Reputation: 1868

I don't know much about the AsEnumerable(), but I would have done it the other way round, something like this:

List<int> intProjFilter = new List<int>();

foreach(string filter in projFilter.Split(','))
       intProjFilter.Add(int.Parse(filter));

from a in dtProj 
where projFilter.Contains(a.ProjectID)
select a;

Let me know if this helps

Upvotes: 1

user1096188
user1096188

Reputation: 1839

String's "contains" isn't really an option here. You should convert projFilter into a proper list of integers first.

var projFilter2 = new HashSet<int>(projFilter.Split(',').Select(i => int.Parse(i)));

and only then check if it contains the desired number.

IEnumerable<DataRow> drProjList = 
    from a in dtProj.AsEnumerable()
    where projFilter2.Contains(a.Field<int>("ProjectId"))
    select a;

Upvotes: 3

Kunal Shah
Kunal Shah

Reputation: 148

I don't know c# well so i am trying to give answer in vb.net hope that will help you.

    Dim dtProj As DataTable
    dtProj = FillProjectList()

    Dim projIdFilter() As Integer = {14, 15, 16}

    Dim drRow = From p In dtProj.AsEnumerable _ 
        Where projIdFilter.Contains(p.Field(Of Integer)("ProjectId")) _
        Select p

Thank you...

Upvotes: 0

Arion
Arion

Reputation: 31239

Maybe something like this:

IEnumerable<DataRow> drProjList =
                       (
                          from a in dtProj.AsEnumerable()
                          where projFilter.Contains(a.Field<int>("ProjectId").ToString())
                          select a;
                       )

Or you can simply do this as well:

IEnumerable<DataRow> drProjList=dtProj.AsEnumerable()
                                    .Where(a=>projFilter
                                          .Contains(a.Field<int>("ProjectId")
                                          .ToString()));

Upvotes: 0

Related Questions