2013-02-06 134 views
0

我需要幫助: 我已經與相關主題嵌套對象:選擇<Thread>對象使用LINQ

public class XNodeViewModel 
{ 
    private int id; 
    private Thread workerThread; 
    private bool _alivingThread; 
    readonly ObservableCollection<XNodeViewModel> _children; 

    private XNodeViewModel(...) 
    { 
     ... 
     if (...) 
     { 
      workerThread = new Thread(DoWork) { IsBackground = true }; 
      workerThread.Start(); 
     } 
    } 
    public ObservableCollection<XNodeViewModel> Children 
    { 
     get { return _children; } 
    } 

    public int Level 
    { 
     get { return _xnode.Level; } 
    } 
    public Thread WorkerThread 
    { 
     get { return this.workerThread; } 
    } 
} 

在WPF後面的代碼我這個視圖模型的引用,我想所有的線程obects相關。 我正在學習LINQ和我知道,有功能的SelectMany扁平化嵌套對象: 一個按鈕,我想停止使用此功能的所有主題:

public void StopAllThread() 
{ 
    //_firstGeneration is my root object 
    var threads = _firstGeneration.SelectMany(x => x.WorkerThread).ToList(); 
    foreach(thread in threads){ 
     workerThread.Abort(); 
    } 
} 

但是,編譯器告訴我:

錯誤1無法從用法推斷方法'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable,System.Func>)'的類型參數。嘗試明確指定類型參數。

只有當我請求鍵入「線程」(如果我要求另一種類型的對象是好的) 我在哪裏做錯了?

+0

嘗試使用Select而不是SelectMany –

+1

請注意,在這種情況下,不應使用「Abort」。在特殊情況下應使用「中止」。考慮使用'Join'來代替'CancelationToken'。 – oleksii

回答

2

您需要使用Select,而不是SelectMany

var threads = _firstGeneration.Select(x => x.WorkerThread); 
foreach(thread in threads) 
    workerThread.Abort(); 

SelectMany用來壓平列表的列表。您的WorkerThread屬性不返回列表,因此SelectMany是錯誤的方法。

+0

謝謝,如果我想扁平化嵌套的對象,我想嘗試:_firstGeneration.SelectMany(x => x.Children).ToList();但它只返回第一級對象。 – davymartu

+0

這是一個不同的問題。請發佈一個新的。 –