How can i change this LINQ query to use my List<int> instead of the hard coded number?

Viewed 62

I finally got my LINQ to query the Datatable and with hard coded values, i get a new datatable with those records. But i need help to update this code to use my List returnClass() as my variables in the where clause.

var query = from r in d.AsEnumerable()
            where r.Field<string>("Column7") == "672"
            select r;

DataTable output = query.CopyToDataTable<DataRow>();
foreach (DataRow row in output.Rows)
{
    output.ImportRow(row);
}

Id like to replace the == "672" with the list i have that contains 94 values, that i want to exclude from the datatable. This is my original post that got me to where i am now, but now i just need help with the LINQ query to use my List and write in a fashion that excludes any records that have the values in my list. Im trying to filter my 34k records down to 29k using that list.

Another example of something i tried that doesnt work

            var query = from r in d.AsEnumerable()
                    where !r.Field<string>("Column7").Contains(Convert.ToString(returnClass()))
                    select r;

        DataTable output = query.CopyToDataTable<DataRow>();
        foreach (DataRow row in output.Rows)
        {
            output.ImportRow(row);
        }

List looks like this(truncated for clarity)

    private List<int> returnClass()
    {
        List<int> cl = new List<int>();
        cl.Add(75);
        cl.Add(76);
        cl.Add(77);
        cl.Add(78);
        cl.Add(79);
        cl.Add(80);
        cl.Add(81);
        cl.Add(82);
        return cl;
    }
1 Answers

Assuming that myList is a List<string>, you can try something like this:

var query = from r in d.AsEnumerable()
            where myList.Any(r.Field<string>("Column7").Contains)
            select r;

Or, if myList is a List<int>, you might want to modify your Database column to also have type int, and you can do the following:

var query = from r in d.AsEnumerable()
            where myList.Contains(r.Field<int>("Column7"))
            select r;
Related