2011-07-22 70 views
2

我正在使用以下Linq-to-XML將一些XML結構加載到我的數據結構中。是否有可能執行Linq將集合作爲HashSet而不是List返回?

// Load all the definitions 
var definitions = doc.Descendants(Constants.ScriptNode) 
        .Select(x => new TcScriptDefinition 
        { 
         Application = x.Attribute(Constants.AppAttribute).Value, 
         CaseName = x.Attribute(Constants.CaseAttribute).Value, 
         ActionType = x.Attribute(Constants.ActionAttribute).Value, 
         ScriptUnit = x.Attribute(Constants.UnitAttribute).Value, 
         ScriptMethod = x.Attribute(Constants.MethodAttribute).Value, 
         Parameters = x.Descendants(Constants.ParamNode) 
             .Select(param => new TcScriptParameter 
             { 
              Code = param.Attribute(Constants.ParamCodeAttribute).Value, 
              ParameterNumber = Convert.ToInt32(param.Attribute(Constants.ParamOrderAttribute).Value), 
              DisplayString = param.Attribute(Constants.ParamDisplayAttribute).Value 
             }) 
             .ToList() 
        }) 
        .ToList(); 

的問題是,所述TcScriptDefinition.Parameters被定義爲HashSet<TcScriptParameter>因此ToList()編譯失敗,因爲它返回一個List<T>

如何通過Linq將我的xml加載到HashSet<T>

回答

2

作爲替代創建ToHashSet一個擴展方法,你也可以只構建HashSet<T>上的蒼蠅,通過改變相關部分:

Parameters = new HashSet<DecendantType>(x.Descendants(Constants.ParamNode) 
            .Select(param => new TcScriptParameter 
            { 
             Code = param.Attribute(Constants.ParamCodeAttribute).Value, 
             ParameterNumber = Convert.ToInt32(param.Attribute(Constants.ParamOrderAttribute).Value), 
             DisplayString = param.Attribute(Constants.ParamDisplayAttribute).Value 
            })) 
+0

我喜歡這兩種方法,但我會將其標記爲答案,因爲它不依賴於我創建擴展方法。 – KallDrexx

+0

@KallDrexx:這就是我提到它的原因。我個人喜歡擴展方法(並且在我的擴展方法庫中),但有時候,像這樣一次性添加它也很好理解。 –

2

有沒有在LINQ沒有ToHashSet<>擴展方法的對象,但它很容易寫一個:

public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) 
{ 
    // TODO: Argument validation here... 
    return new HashSet<T>(source); 
} 

當你正在處理一個名爲類型你可以調用構造函數明確的過程,但擴展方法最終看起來更清潔。

我真的很想在框架中看到這個 - 它是一個方便的小額外運算符。

+0

在IEnume即使世界一個錯字* R *能。不幸的是,由於SO政策,我無法糾正它。 – Christoph

+0

@Christoph:固定,謝謝。 –

相關問題