lambda表达式,用于对从一个表返回记录的两个表进行查询

时间:2010-05-03 15:32:23

标签: wpf data-binding lambda

我有两张桌子

TableA (articles)
int id
int Type
string name

TableB (compatibles)
int linked_ID
int tableA_ID

TableA records:
id=1, Type=0, name="ArticleA"
id=2, Type=1, name="ArticleB"
id=3, Type=2, name="ArticleC"
id=4, Type=1, name="ArticleD"

TableB records:
linked_ID= 1, tableA_ID=2
linked_ID= 1, tableA_ID=3
linked_ID= 1, tableA_ID=4

TableB有一个与某篇文章兼容的弧形列表。我对查询很新(在我的项目中不需要它们)。但是,由于C#和WPF允许使用Binding进行一些非常酷的自动化,我想添加一个返回以下内容的绑定:

向我提供所有类型1且与我选择的文章(id = 1)兼容的文章。

它的简单部分运作良好(文章列出了所有文章):

private ObservableCollection<Article> _articles = 
    new ObservableCollection<Article>();

[填写可用文章] 然后:

comboBoxArticles.ItemsSource = 
    _articles.AsBindable().Where( c => c.Typ == 0 );

如何扩展Where子句以查询另一个表?

提前多多感谢。

1 个答案:

答案 0 :(得分:0)

看起来好像你想使用Linq“加入”两个“表”。这是让你入门的东西:

comboBoxArticles.ItemsSource =
    from article in _articles
    from compatible in _compatibles
    where article.Type == 0 && && article.id == compatible.tableA_ID && compatible.linked_ID == 1
    select article;

......或方法链......

comboBoxArticles.ItemsSource = _articles
    .SelectMany(article => _compatibles, (article, compatible) => new {article, compatible})
    .Where(@t => @t.article.Type == 0 && @t.article.id == @t.compatible.tableA_ID && @t.compatible.linked_ID == 1)
    .Select(@t => @t.article);