Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridVIew populated with anonymous type, how to filter?

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);
}
like image 911
gremo Avatar asked Dec 01 '10 06:12

gremo


1 Answers

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();
like image 152
Marc Gravell Avatar answered Sep 29 '22 11:09

Marc Gravell