Reputation: 39
I can't fill a datagrid with this code:
var y = valores.Where(c => c % 2 == 0);
dataGridView1.DataSource = y.ToList();
But this works:
var x = from valor in valores
where (valor % 2 == 0)
select new
{
valor
};
dataGridView1.DataSource = x.ToList();
Upvotes: 2
Views: 370
Reputation: 76
As you may see from the result of your queries:
you are getting two different lists. The first one returns the integers value type, the second one is returning valor which is anonymous type list.
In order to fix the first query you should edit your code from:
var y = valores.Where(c => c % 2 == 0);
to
var y = valores.Where(c => c % 2 == 0).Select(c => new { valor = c });
Upvotes: 1
Reputation: 3018
I can't fill a datagrid
Apparently you mean that your dataGridView1
is not displaying the list.
I reproduced your problem and did an experiment with some types. Looks like the reason is when the list contains objects which has no properties then DataGridView
does not get bound to the list. In your first snippet, for example, the Linq expression is returning a list of integers, which is System.Int32
. And if you take a look at the definition of this value type with object browser then you can see that it does not declare any public property.
For example following code "does not work" either
var x = from valor in valores
where (valor % 2 == 0)
select new
{
};
dataGridView1.DataSource = x.ToList();
That is, I am creating object of anonymous type with no properties.
Like System.Int32
a list of System.Double
or System.Decimal
"does not work" either.
Unlike System.Int32
a list of System.DateTime
s works because DateTime
has properties.
So my conclusion is if a type does not contain any property then a list of instances of this type will not be bound to the DataGridView
.
Upvotes: 1