Linq BoilerPlate:全部需要吗? [英] Linq BoilerPlate: Is all of it needed?

查看:77
本文介绍了Linq BoilerPlate:全部需要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可以正常工作:

I have the following code, which does work:

var dataSource = (from p in dv.ToTable().AsEnumerable() where filter(p) select p).AsDataView();

filterFunc<DataRow, bool>
dvDataView
dataSource用作DataGridDataSource.

filter is a Func<DataRow, bool>
dv is a DataView
dataSource is being used as a DataSource for a DataGrid.

无论如何,我打电话给ToTableAsEnumerableAsDataView有点不舒服,所以我想知道是否有办法减少电话数量.

Anyhow, it strikes me as a bit ugly that I am calling ToTable, AsEnumerable, and AsDataView, so I was wondering if there is a way to reduce the number of calls.

这能做到吗?

编辑:DataGrid具有分页功能,我利用dataSource确定条目总数.我并不特别担心这样做的效率. dv只有几千个项目,并且该表正在内存中维护.

The DataGrid has pagination, and I make use of the dataSource to determine the total number of entries. I'm not especially worried about the efficiency of this; dv only has a few thousand items and the table is being maintained in memory.

推荐答案

一件事,我想说在这里使用查询表达式有点笨拙.您的代码等效于:

Well for one thing, I'd say that using a query expression is somewhat clumsy here. Your code is equivalent to:

var dataSource = dv.ToTable()
                   .AsEnumerable()
                   .Where(filter)
                   .AsDataView();

我想说的更清楚.

另一种选择是:

var dataSource = dv.Cast<DataRowView>()
                   .Select(rowView => rowView.Row)
                   .Where(filter)
                   .ToList();

这避免了构建DataTable,因此也可能会更加高效(它将从视图中流式传输DataRowView s并选择其基础的DataRow s),但最后会构建一个List<DataRow> .另一方面,它实际上不是在视图本身上起作用,因为它只是在选择基础行.这可能会或可能不会满足您的需求,具体取决于您的视图在做什么.

This avoids building a DataTable, so may well be more efficient too (it'll just stream the DataRowViews from the view and select their underlying DataRows) but builds a List<DataRow> at the end. On the other hand, it's now not acting on the view itself, really - because it's just selecting the underlying rows. This may or may not do what you need, depending on what your view is doing.

这篇关于Linq BoilerPlate:全部需要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆