Best linq questions in August 2011

Searching a tree using LINQ

21 votes

I have a tree created from this class.

class Node
{
    public string Key { get; }
    public List<Node> Children { get; }
}

I want to search in all childrens and all their childrens get the ones matching one condition:

node.Key==SomeSpecialKey

How can I implement it?

It's a misconception that this requires recursion. It will require a stack or a queue and the easiest way is to implement it using recursion. For sake of completeness I'll provide a non-recursive answer.

    static IEnumerable<Node> Descendants(Node root)
    {
        var nodes = new Stack<Node>(new[] {root});
        while (nodes.Any())
        {
            Node node = nodes.Pop();
            yield return node;
            foreach (var n in node.Children) nodes.Push(n);
        }
    }

Use this expression for example to use it:

 Descendants(root).Where(node => node.Key == SomeSpecialKey)

What's the benefit of .Cast over .Select?

16 votes

I have a type with implicit conversion operators to most base types and tried to use .Cast<string>() on a collection of this type, which failed. As I dug into it, I noticed that casting via as doesn't use implicit or explicit conversion and just won't compile, so I guess that's where .Cast falls down. So this fails

var enumerable = source.Cast<string>();

but this works

var enumerable = source.Select(x => (string)x);

So what's the benefit of Cast? Sure, it's a couple of characters shorter, but seems a lot more limited. If it can be used for conversion, is there some benefit other than the more compact syntax?

Cast usage

The benefit of Cast comes when your collection only implements IEnumerable (ie. not the generic version). In this case, Cast converts all elements to TResult by casting, and returns IEnumerable<TResult>. This is handy, because all the other LINQ extension methods (including Select) is only declared for IEnumerable<T>. In code, it looks like this:

IEnumerable source = // getting IEnumerable from somewhere

// Compile error, because Select is not defined for IEnumerable.
var results = source.Select(x => ((string)x).ToLower());

// This works, because Cast returns IEnumerable<string>
var results = source.Cast<string>().Select(x => x.ToLower());

Cast and OfType are the only two LINQ extension methods that are defined for IEnumerable. OfType works like Cast, but skips elements that are not of type TResult instead of throwing an exception.

Cast and implicit conversions

The reason why your implicit conversion operator is not working when you use Cast is simple: Cast casts object to TResult - and your conversion is not defined for object, only for your specific type. The implementation for Cast is something like this:

foreach (object obj in source)
    yield return (TResult) obj;

This "failure" of cast to do the conversion corresponds to the basic conversion rules - as seen by this example:

YourType x = new YourType(); // assume YourType defines an implicit conversion to string
object   o = x;

string bar = (string)x;      // Works, the implicit operator is hit.
string foo = (string)o;      // Fails, no implicit conversion between object and string

Can't convert this into VB.net

4 votes

I'm trying to convert the following into vb.net. Thanks in advance

   Categories.DataSource = objDT.Rows.Cast<DataRow>()
        .Select(r => new { Attendee = r.Field<string>("Attendee"), Item = r.Field<string>("Item") })
        .GroupBy(v => v.Attendee)
        .Select(g => new { Attendee = g.Key, Item = g.ToList() });

This is where I get stuck, I have tried two different methods but still nothing works:

Categories.DataSource = objDT.AsEnumerable() _
    .Select(Function(r) New With {.Attendee = r.Field(Of String)("Attendee"), .Item = r.Field(Of String)("Item")}) _
    .GroupBy(Function(v) v.Field(Of String)("Attendee")) _
    .Select(Function(g) Attendee = g.Key)

or

Categories.DataSource = objDT.Rows.Cast(Of DataRow)().AsEnumerable _
    .Select New Object(){ Function(r As DataRow) Attendee = r.Field(Of String)("Attendee"), Item = r.Field(Of String)("Item")} _
.GroupBy( Function(v) v.Category) _
.Select( Function(g) new { Category = g.Key, Numbers = g.ToList() }

Try this :

  Categories.DataSource = objDT.Rows.Cast(Of DataRow)().Select(Function(r) New With { _
 .Attendee = r.Field(Of String)("Attendee"), _
 .Item = r.Field(Of String)("Item") _
}).GroupBy(Function(v) v.Attendee).Select(Function(g) New With { _
 .Attendee = g.Key, _
 .Item = g.ToList() _
})

Object Class (New Object() With {})is different than anonymous type (New With {}).

You can use this site in the future : http://www.developerfusion.com/tools/convert/csharp-to-vb/ . It works pretty well for most of the conversions.