开发者

Is it possible to perform Linq to return a collection as a HashSet instead of a List?

I am using the following Linq-to-XML to load some XML structures into my data structures.

    // 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();

The problem is that the TcScriptDefinition.Parameters is defined as a HashSet<TcScriptParameter> and thus the ToList() fails to compile since it returns a List<T>.

How can I load my xml into a HashSet<T> via Lin开发者_运维技巧q?


As an alternative to creating an extension method for ToHashSet, you can also just construct the HashSet<T> on the fly, by changing the relevant section to:

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
                                   }))


There's no ToHashSet<> extension method in LINQ to Objects, but it's easy to write one:

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

When you're dealing with a named type you can just call the constructor explicitly of course, but the extension method ends up looking a bit cleaner.

I would really like to see this in the framework - it's a handy little extra operator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜