[英]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.