1

How can i use dynamic columns on Linq?

For example;

var tmp = (from i in ESE.viw_kisiler
                         where (i.i_want_to_use_dynamic_column_in_here.Contains(kelime))
                         select i);

Other example;

 var a = (ComboBoxItems)ComboBox1.SelectedItem;
    var ColumnName = a.Value;

        var tmp = (from i in ESE.viw_kisiler
                                 where (i.ColumnName.Contains(kelime))
                                 select i);

Thanks for all.

Ahmet YETİK
  • 71
  • 3
  • 9

2 Answers2

1

Make use of dynamic linq library : Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library) or predicate builder

enter image description here

you can also check : Dynamic query with Linq article on blog.

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • I read your wrote. May you look my example. I wanna use .Contains Thanks. – Ahmet YETİK Sep 21 '11 at 12:15
  • @user956872 - i think dynamic linq library easily satify your need – Pranay Rana Sep 21 '11 at 12:17
  • I saw a lot of examples. But still so methods are very very different. For exaple its working; _ESE.viw_kisiler.Where(a => a.ad.Contains(kelime))_ But still so i cant use dynamic column name. Thaks. – Ahmet YETİK Sep 21 '11 at 12:23
  • Try var tmp = ESE.viw_kisiler.Where(String.Format("{0}.Contains(\"{1}\")", ColumnName , kelime)); – sgmoore Sep 21 '11 at 17:36
  • @sgmoore its giving error. `System.Data.EntitySqlException was unhandled cannot be resolved into a valid type of function. Near simple identifier.` Thanks. – Ahmet YETİK Sep 22 '11 at 06:37
1

Thanks for your all replies and comments.

I use a different method;

var SQL1 = (from i in ESE.viw_kisiler
                           select i);

                DataTable DT = LINQToDataTable(SQL1);

                var SQL2 = (from t in DT.AsEnumerable()
                         where t.Field<string>(ColumnName).Contains(Word)
                         select t);

First of all i was convert Linq Query a DataTable and then i try this codes. It was working now!

Ahmet YETİK
  • 71
  • 3
  • 9
  • There was a "case insensitive" about Contains method. I resolve it via StringComparison and an extension method. `public static bool Contains(this string source, string toCheck, StringComparison comp) { return source.IndexOf(toCheck, comp) >= 0; }` `where t.Field(ColumnName).Contains(Word, StringComparison.InvariantCultureIgnoreCase)` – Ahmet YETİK Sep 22 '11 at 09:05
  • http://stackoverflow.com/questions/444798/case-insensitive-containsstring/4217362#4217362 – Ahmet YETİK Sep 22 '11 at 09:12
  • http://blogs.msdn.com/b/jmanning/archive/2008/02/25/string-contains-really-should-have-an-overload-with-stringcomparison-specified.aspx – Ahmet YETİK Sep 22 '11 at 09:14
  • It's a good angle. How does the LINQToDataTable work in this case? Is there any code or library that does this conversion? – liang Apr 16 '13 at 04:18