【问题标题】:DataGridVIew populated with anonymous type, how to filter?DataGridVIew 填充匿名类型,如何过滤?
【发布时间】:2011-05-18 07:57:56
【问题描述】:

我使用返回匿名类型的 LINQ 查询填充了 DataGridView。

问题:是否有机会过滤其数据源实际上是匿名的 DataGridView?

// 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);
}

【问题讨论】:

    标签: c# linq datagridview datasource anonymous-types


    【解决方案1】:

    如果您继续这样做(解释)“DataSource = DataSource.Where(...)”,您将在内部重复过滤过滤后的数据;但在这种情况下,我会:

    a:将列表存储在一个字段中以供重复使用,

    b: 不是我们匿名的类型

    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();
    

    【讨论】:

    • 是的,我错了,我要过滤已经过滤的数据。这是正确的。但我想知道如何使用匿名类型来做到这一点......
    • @Gremo - 一种叫做逐例投射的技巧,但这并不值得,真的。严重地;不要在这里使用匿名类型。它们仅在数据在相同上下文中生成和使用时才有意义(或被诸如反射之类的东西使用)。这不是这里的情况。您也可以通过反射进行过滤,但这很慢并且很脆弱。
    • 好吧,我会暴露领域。我同意你关于反思的看法……不值得……
    • @Gremo - 该字段不必是公开的(如果 expose 你的意思是公开的)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 2012-01-02
    • 2011-09-05
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多