I've populated a DataGridView with a LINQ query which returns an anonymous type.
Question: any chance to filter the DataGridView whose data source is actually anonymous?
// Setting the datagridview data source
rawDocumentsDataGridView.DataSource = rawTopics
.SelectMany(t => t.Documents)
.Select(d => new
{
DocumentId = d.Id,
Rilevante = d.IsRelevant,
TopicId = d.Topic.Id // foreign key
}).ToList();
// Make it not visibile, waiting for master change
rawDocumentsDataGridView.Visible = false;
// When master selection changed...
void rawTopicsDataGridView_SelectionChanged(object sender, System.EventArgs e)
{
if (rawTopicsDataGridView.CurrentRow == null) return;
// Get selected topic id
int tid = (int) rawTopicsDataGridView.CurrentRow.Cells["TopicId"].Value;
// Filter rawDocumentsDataGridView based on topic id
// WARNING: PSEUDO CODE
var oldDataSource = (List<AnonymousType>)rawDocumentsDataGridView.DataSource;
rawDocumentsDataGridView.DataSource = oldDataSource
.Where(d => d.TopicId == tid);
}
If you keep doing that (paraphrasing) "DataSource = DataSource.Where(...)" you are going to be filtering inside the filtered data repeatedly; but in this case I would:
a: store the list in a field for re-use, and
b: not us an anonymous type
class DocumentRow {
public int DocumentId {get;set;}
public bool Rilevante {get;set;}
public int TopicId {get;set;}
}
...
List<DocumentRow> allData;
...
allData = rawTopics.SelectMany(t => t.Documents)
.Select(d => new DocumentRow
{
DocumentId = d.Id,
Rilevante = d.IsRelevant,
TopicId = d.Topic.Id // foreign key
}).ToList();
...
rawDocumentsDataGridView.DataSource = allData
.Where(d => d.TopicId == tid).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With