[英]DataGridVIew populated with anonymous type, how to filter?
I've populated a DataGridView with a LINQ query which returns an anonymous type. 我已经使用LINQ查询填充了DataGridView,该查询返回匿名类型。
Question : any chance to filter the DataGridView whose data source is actually anonymous? 问题 :是否有机会过滤其数据源实际上是匿名的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);
}
If you keep doing that (paraphrasing) "DataSource = DataSource.Where(...)" you are going to be filtering inside the filtered data repeatedly; 如果你继续这样做(意译)“数据源= DataSource.Where(......)”你将要过滤的数据内反复过滤; but in this case I would:
但在这种情况下,我会:
a: store the list in a field for re-use, and a:将列表存储在字段中以供重用, 以及
b: not us an anonymous type 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.