使用List< SomeObject>连接DataTable. [英] Join DataTable with List<SomeObject>
问题描述
我有一个DataTable和一个对象列表.我需要返回DataTable中的所有行,其中List中的属性是某个值.列表仅用于过滤数据表(但数据表中不包含过滤器列).
I have a DataTable and a List of objects. I need to return all rows in the DataTable where a property in the List is a certain value. The List is only used for filtering the datatable (but the filter column isn't containined in the datatable).
我确定这对于LINQ是必须的.
I'm sure this must be possible with LINQ.
数据表包含:
MembershipID Username Password
1 blah blah
2 blah blah
3 blah blah
我的列表包含:
MembershipID Profile1 Profile2 Profile3 DifferentID
1 blah blah blah A
2 blah blah blah B
3 blah blah blah C
我需要返回(作为数据表)-例如:对于GetUsersByDifferentID("B"):
I need to return (as a DataTable) - eg: for GetUsersByDifferentID("B"):
MembershipID Username Password
2 blah blah
...
如果这样可以使第二张表更容易获得,那么我可以将它作为DataTable获得,但是我认为使用LINQ可以实现我所需要的.我只是无法理解魔术语法.
I could get the second table as a DataTable if that would make it easier, but I think what I need is possible with LINQ. I just can't get my head around the magic syntax.
推荐答案
您可以使用联接来实现:
You can do it using a join:
List<ListItem> listItems = //whatever
DataTable dtItems = //whatever
IEnumerable<DataRow> matchingRows = listItems
.Join( dtItems.AsEnumerable(),
listItem => listItem.MembershipID,
row => row.Field<int>("MembershipID"),
(r,li) => new { DifferentId = li.DifferentId, Row = r })
.Where( ji => ji.DifferentID == "B")
.Select( ji => ji.Row);
更改where子句以使用要匹配的实际值...
Change the where clause to use the actual value you want to match...
这篇关于使用List< SomeObject>连接DataTable.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!