我想得到"thisValueIwant“的价值。能这么容易地得到这个值吗?或者这2 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 ???)
}
}发布于 2017-06-07 09:09:44
因为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();发布于 2017-06-07 10:06:17
ObservableCollection<T>是实现IEnumerable<T>的Collection<T>。因此,您的FooCollection是一个可观察的集合这一事实并不重要,您可以将其看作是Foo、IEnumerable<Foo>和IEnumerable<FooInFoo>的序列。
您的代码将类似于(对不起,我只知道如何以方法格式编写):
IEnumerable<Foo> AllFooWithNumber1 = FooCollection
.Where(foo => foo.Number == 1);如果您确定确实有一个继续:
Foo fooWithNumber1 = AllFooWithNumber1.Single();如果您不确定是否存在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;如果你不确定是否有一个单一的元素,可能会出现问题。
如果要检查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);发布于 2019-11-19 12:08:12
你可能需要我的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 wantX是INotifyPropertyChanged,并通知您计算结果的变化。不要忘记通过INotifyPropertyChanged接口将上述代码中提到的所有属性通知更改。
https://stackoverflow.com/questions/44408174
复制相似问题