-1

Relatively new to C# and started using Dynamic LINQ to filter a data table adapter using a string. The issue I'm having is that the Where clause only seems to evaluate the first value in the string and none of the others. Here is the code I am using.

        string[] ids = new string[] { "12345", "67891", "45878" };
        var resultQ = (from pr in table1 select pr).AsQueryable();
        var iq = resultQ.Where("@0.Contains(FieldName)", ids);  

It works but only for the first value "12345" so the output of iq displays all fields for "12345". I tried using linq.dynamic.core to see if that would help but the still same result (or I haven't used it properly). I know I'm probably missing something minor here but any help would be greatly appreciated.

Also on a separate note: I wanted to convert the end result of iq which is a IQueryable type to EnumerationRowCollection type. Is this possible?

Thanks in advance

Lawrence
  • 21
  • 2
  • 1
    What are `pr` and `table1` variables? Please, provide fully reproducible code. – kosist Oct 05 '20 at 05:00
  • Hi, table1 refers to the table adapter (table1 = TableAdapter1.GetData();) and pr is just a range variable used for rows. That isn't the issue it is to do with the dynamic LINQ contain statement not picking up all the values in the array. Cheers – Lawrence Oct 05 '20 at 05:10
  • 1
    Please share a [mcve]. – mjwills Oct 05 '20 at 06:12

2 Answers2

1

Managed to fix both points now. Either set string[] to string for dynamic LINQ to get all values in list as coded below

string ids =  "12345,67891,45878";
var resultQ = (from pr in table1 select pr).AsQueryable();
var iq = resultQ.Where("@0.Contains(FieldName)", ids); 

or use Syed's suggestion and change the LINQ query and keep the array (thanks again Seyed)

For the conversion of IQueryable type to EnumerationRowCollection I changed EnumerationRowCollection to IEnumerable and this worked for all my LINQ queries

Thanks

Lawrence
  • 21
  • 2
0

Just use this. It will works fine.

string[] ids = new string[] { "12345", "67891", "45878" };

var resultQ = (from pr in table1 select pr).AsQueryable();

var iq = resultQ.Where(w => ids.Contains(w.Id)).ToList();
Syed Md. Kamruzzaman
  • 979
  • 1
  • 12
  • 33
  • Awesome thanks Syed, that works too! I also wanted to convert that iq list to EnumerableRowCollection type is this possible? cheers – Lawrence Oct 05 '20 at 06:15
  • Welcome. ToList will not fulfil your requirement? what you want then let me know – Syed Md. Kamruzzaman Oct 05 '20 at 07:01
  • I wanted to use iq in another LINQ method to group by and sum. I have added the LINQ method into a function to be used in a number of different places with parameters but I get a "lamda expression with statement body cannot be converted to expression tree " when I use the following. Works without using IQueryable .Select(g => { DataRow row = table1.NewRow(); row[field] = g.Key; row[aggr] = g.Sum(r => r.Field(aggr)); – Lawrence Oct 05 '20 at 08:10