Wednesday, March 16, 2011

How to Query A DataGridView Using Linq

I have a DataGridView that I want to query using Linq (C# WinForm). I want to "count" rows where a certain criteria is met. For example,

variable1 = "count rows where ColumnBoxAge > 3 || < 5"

label1.Text = variable1

How to do this in C# WinForm using Linq?

From stackoverflow
  • I don't know if it could work but you can try this;

    dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 ||
         c.Field<int>("ageColumn") < 5).Count();
    

    Edit : Where instead of Select.

    MarlonRibunal : it's counting all rows in the dgv...not what I want. Shld be "count rows where BoxAge is between 3 and 5"...
    MarlonRibunal : Now that's working...(See Edit)
  • So your query is wrong! Try to put '&&' instead of '||';

    dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 &&
         c.Field<int>("ageColumn") < 5).Count();
    

    Edit : Where instead of Select.

  • @yapiskan

    dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 &&
         c.Field<int>("ageColumn") < 5).Count();
    

    .Where instead of .Select

    Thank you very much! I appreciate your help.

    yapiskan : Oops, sure it is!

0 comments:

Post a Comment