【发布时间】:2010-10-29 04:16:29
【问题描述】:
我正在尝试测试 LINQ 到底能走多远。我想要实现的是使用单个表达式而不是 for 循环对对象列表进行属性分配。我想获取 listA 中的所有项目并更新 IsMatched 属性,但只有在 listB 中有相应项目的地方(这是不同的类型),这可能吗?
示例代码:
public struct A { public int x; public bool IsMatched;}
public struct B {public int x;}
static void Main(string[] args)
{
List<A> listA = new List<A>();
List<B> listb = new List<B>();
listA.Add(new A() { x=1});
listA.Add(new A() { x=2});
listA.Add(new A() { x=3});
listb.Add(new B() { x=2});
listb.Add(new B() { x=3});
listA = listA.SelectMany(fb => listb, (fb, j) => new {a=fb, b=j})
.Where (anon => anon.b.x == anon.a.x).Select(anon => new A() {x=anon.a.x, IsMatched=true})
.ToList(); // this does not do what I want.
}
我尝试过使用 SelectMany,但这只会返回匹配的项目,或者我不想要的笛卡尔积。
【问题讨论】:
标签: linq