Solved

adding a variable column name to linq query

Posted on 2011-03-23
6
675 Views
Last Modified: 2012-05-11
Hi,

I've been trying to get the below query to work with a variable column name, can anyone help me out please?

the "where tbl.columnname.Trim().Length > 0" part was my way of making it ignore cells with a value of 0 or null..
string columnname = "thecolname";

var results = from tbl in query
                          where tbl.columnname.Trim().Length > 0
                          group tbl by tbl.columnname into g
                          select new { var_text = g.Key, var_count = g.Count() };

Open in new window

0
Comment
Question by:OTM
  • 2
  • 2
  • 2
6 Comments
 
LVL 53

Expert Comment

by:Dhaest
ID: 35199040
Did you try it through the datacolumn ?


var results = from tbl in query
                          where tbl(columnName).ToString().Trim().Length > 0
                          group tbl by tbl(columnName) into g
                          select new { var_text = g.Key, var_count = g.Count() };
0
 

Author Comment

by:OTM
ID: 35199197
Thanks dhaest, but it does't work, i get an error on the 2nd line of the query.

the query would basically create a list like this when being used for a gridview datasource:

var_text  var_count
type1      3
type2      5
type3      2

the table being read from would be this:
type1    
type1
type1
type2
type2
type2
type2
type2
type3
type3
0
 
LVL 2

Expert Comment

by:ericpeckham
ID: 35219462
Sorry, but I don't think you can use Linq to Sql that way.  It generates the Sql at compile time, so just as you can't do this in direct Sql, you can't do it with Linq.

You're stuck with using direct SQL, which the following page describes how to use in a Linq to Sql environment:  http://msdn.microsoft.com/en-us/library/bb399403.aspx
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:OTM
ID: 35253447
ok thanks guys,

i've decided to just use an if statement to specify different queries based on a parameter.. works fine but lots more lines of code.. i was sure this was possible
0
 
LVL 53

Accepted Solution

by:
Dhaest earned 500 total points
ID: 35253668
I finally had some time to adjust the query.  In code below I just create a simple datatable with 2 columns and fill them with data. Afterwards, I just pass the columnname for which I want to group

And here it works :)

result of first query:
+            [0]      { var_text = "type1", var_count = 2 }      <Anonymous Type>
+            [1]      { var_text = "type2", var_count = 4 }      <Anonymous Type>
+            [2]      { var_text = "type3", var_count = 1 }      <Anonymous Type>

Result of second query:
+            [0]      { var_text = "type6", var_count = 2 }      <Anonymous Type>
+            [1]      { var_text = "type5", var_count = 4 }      <Anonymous Type>
+            [2]      { var_text = "type4", var_count = 1 }      <Anonymous Type>

DataTable query = new DataTable("query");
            query.Columns.Add("col1");
            query.Columns.Add("col2");
            DataRow row;
            for (int i = 0; i<2;i++)
            {
                row = query.NewRow();
                row["col1"]="type1";
                row["col2"] = "type6";
                query.Rows.Add(row);
            }
            for (int i = 0; i<4;i++)
            {
                row = query.NewRow();
                row["col1"]="type2";
                row["col2"] = "type5";
                query.Rows.Add(row);
            }
            for (int i = 0; i<1;i++)
            {
                row = query.NewRow();
                row["col1"]="type3";
                row["col2"] = "type4";
                query.Rows.Add(row);
            }

            string columnName = "col1";

            var results = from tbl in query.AsEnumerable()
                          where tbl[columnName].ToString().Trim().Length > 0
                          group tbl by tbl[columnName] into g
                          select new { var_text = g.Key, var_count = g.Count() };

            columnName = "col2";

            results = from tbl in query.AsEnumerable()
                          where tbl[columnName].ToString().Trim().Length > 0
                          group tbl by tbl[columnName] into g
                          select new { var_text = g.Key, var_count = g.Count() };

Open in new window

0
 
LVL 2

Expert Comment

by:ericpeckham
ID: 35260533
That's impressive, Dhaest.  I guess I was stuck in "Linq to Sql" mode, thinking that it wouldn't work when querying a Sql database.  I still don't think it would, but as OTM may not be querying a Sql database, then you should win the prize!  I'd be really interested to know if this is possible with Linq to Sql.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
LINQ question 7 22
Hovering effect 9 29
Check my code out(2) 1 33
Adjust the position 3 13
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now