2011-01-19 43 views
2

我需要实现这样的查询复杂的表达式加盟:在C#中LINQ2SQL声明本可以写成这样:如何使用使用LINQ2SQL C#表达式

var query = from f1 in Foo 
      from f2 in Foo 
      where f1.Id < f2.Id && f1.Value == f2.Value 
      select f1; 

但我不知道如何使用C#表达式来做到这一点。我的意思是这样的:

var query = Foo.Join(...).Select(...); 

我看到,加入方法使机会只用等于加入f1.Id == f2.Id。但是如何在C#表达式中编写更复杂的查询表达式,例如这样的表达式呢?

+0

什么是c1和c2?而你的加入没有条款... – 2011-01-19 19:16:57

+0

对不起,应该是f1.Value == f2.Value – Dao 2011-01-19 19:19:39

回答

1

虽然otheranswers会产生相同的结果,它不将其语义转换为原始查询语法。

如果你想要的东西在语义上更接近原始查询语法,你可以使用SelectMany扩展方法,因为这是查询语法转换,当你有一个以上的from子句:

var query = Foo. 
    // from f1 in Foo 
    // from f2 in Foo 
    // 
    // Need the anonymous type to carry over the two items 
    // in the sequences, the compiler will do the same 
    // in your original query, although the names 
    // will be much more mangled. 
    SelectMany(f => Foo, (f1, f2) => new { f1, f2 }). 

    // f1.Id < f2.Id && f1.Value == f2.Value 
    Where(f => f.f1.Id < f.f2.Id && f.f1.Value == f.f2.Value). 

    // select f1; 
    Select(f => f.f1); 

而且,应该注意的是,虽然你可以使用Join方法,但是你可以只使用在你想要基于相等性的内部连接语义的情况下使用它。除此之外,您必须使用SelectMany并致电Where

1

有没有直接转换,因为你原来的查询使用的不是加入...但我认为这可能让你接近:

var query = Foo.Join(Foo, 
        f1 => f1.Value, 
        f2 => f2.Value, 
        (f1, f2) => new { f1, f2 }) 
       .Where(g => g.f1.Id < g.f2.Id) 
       .Select(g => g.f1); 
+0

@Justin Niessner:有一个直接转换,`SelectMany`和匿名类型。 – casperOne 2011-01-19 19:45:03

0

如果您重新排列查询,您可以使用表达式语法,该语法简单且易读。如何加入.Value属性并在f1.Id < f2.Id上过滤?这应该提供你正在寻找的结果。

var query = from f1 in Foo 
      join f2 in Foo on f1.Value equals f2.Value 
      where f1.Id < f2.Id 
      select f1;