[英]Linq in from ObservableCollection in ObservableCollection
我试图获得值“thisValueIwant”。 有没有可能这么容易地得到这个值? 或者也许这两个 ObservableCollection 有另一种解决方案
public class Foo
{
public int number { get; set; }
public ObservableCollection<FooInFoo> Details { get; set; }
}
public class FooInFoo
{
public string thisValueIwant { get; set; }
}
public class TestClass
{
public void Test()
{
ObservableCollection<Foo> FooCollection = new ObservableCollection<Foo>();
FooCollection.Add(new Foo{
number =1,
Details = new ObservableCollection<FooInFoo>{ new FooInFoo {thisValueIwant = "very important string"}}
});
string x = (from f in FooCollection
where f.number == 1
select ???)
}
}
由于ObservableCollection<FooInFoo> Details
是一个集合,你必须决定你想要的细节:第一个、最后一个、任何一个或全部。
假设你想要第一个:
var d = FooCollection.Where(f => f.Number == 1).FirstOrDefault()?.Details.FirstOrDefault()?.thisValueIwant;
或者最后一个:
var d = FooCollection.Where(f => f.Number == 1).FirstOrDefault()?.Details.LastOrDefault()?.thisValueIwant;
或全部(具体化为数组):
var ds = FooCollection.Where(f => f.Number == 1).FirstOrDefault()?.Details.Select(d => d.thisValueIwant).ToArray();
ObservableCollection<T>
是实现IEnumerable<T>
的Collection<T>
IEnumerable<T>
。 因此,您的FooCollection
是一个可观察集合这一事实并不重要,您可以将其视为Foo
、 IEnumerable<Foo>
和IEnumerable<FooInFoo>
您的代码将类似于(对不起,我只知道如何以 Method 格式编写)在婴儿步骤中:
IEnumerable<Foo> AllFooWithNumber1 = FooCollection
.Where(foo => foo.Number == 1);
如果您确定确实有一个继续:
Foo fooWithNumber1 = AllFooWithNumber1.Single();
如果您不确定是否存在SingleOrDefault ,请考虑使用SingleOrDefault 。
获得所需的 Foo 后,您可以选择详细信息:
IEnumerable<FooInFoo> detailsOfFooWithNumber1 = fooWithNumber1.Details;
FooInFoo detailIWant = detailsOfFooWithNumber1
.Where(detail => some expression that uses detail...)
.SingleOrDefault();
string thisValueIWant = defailtIWant.thisValueIWant;
或者在一个声明中:
string thisValueIWant = FooCollection
.Where(foo => foo.Number == 1)
.Single()
.Details
.Where(detail => ...)
.Single()
.thisValueIWant;
如果您不确定是否只有一个 Single 元素,则可能会出现问题。
如果要检查给定值的 foo.Number 和某些谓词的所有详细信息,请考虑使用Enumerable.SelectMany 。 只要您有序列序列(数组中的数组),就会使用它。 使用 SelectMany 您可以枚举所有这些内部数组,就好像它是一个数组一样:
IEnumerable<string> valuesIWant = FooCollection
.Where(foo => foo.Number == 1)
.SelectMany(foo => foo.Details)
// now you have one sequence of all FooInFoo that are Details within
// Foo objects with Number 1
.Where(detail => expression that selects the FooInFoo you want)
.Select(detail => detail.thisValueIWant);
你可能需要我的ObservableComputations库。 使用这个库,你可以这样编码:
Expression<Func<string>> expr = () =>
FooCollection
.Filtering(а => f.number == 1)
.FirstComputing().Value
.Using(f => f != null
? f.Details.FirstComputing().Using(fif =>
fif.Value != null ? fif.Value.thisValueIwant : null).Value
: null).Value;
Computing<string> x = expr.Computing();
// x.Value is what you want
x 是INotifyPropertyChanged并通知您 expr 计算结果的变化。 不要忘记让上面代码中提到的所有属性通过INotifyPropertyChanged接口通知更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.