2
  1. The Problem

I want to convert a foreach loop to a linq statement.

  1. The Details

I have the following unity class (from metadata, removed most of the functions)

public class Transform : Component, IEnumerable
{
    public IEnumerator GetEnumerator();
}

I have a local variable of this class (inherited) in my own class, which is

Transform transform;

On this I can do

List<Transform> children = new List<Transform>();
foreach (Transform t in transform)
    children.Add(t);

How can I do the same in a Linq expression?

Fattie
  • 27,874
  • 70
  • 431
  • 719
Andreas Reiff
  • 7,961
  • 10
  • 50
  • 104
  • 1
    Avoid `var` if you want us to understand your question. – Tim Schmelter Feb 02 '16 at 12:39
  • 1
    Does `children = transform.Cast().ToList();` work for you? – Enigmativity Feb 02 '16 at 12:40
  • I will edit, though the type is directly on the right side. – Andreas Reiff Feb 02 '16 at 12:40
  • 1
    I think it reads better with the `var`. – Enigmativity Feb 02 '16 at 12:41
  • `Transform` is a class that contains `Transforms`? Or did you mean `children.Add(t.gameObject);` under point #2, instead of `children.Add(t);`? – CompuChip Feb 02 '16 at 12:41
  • @Enigmativity Normally, you're right. But to Tim's point, we don't have Intellisense or the other code to look at and tell us what those variables are. So if the assignments and variable names are not clear as to what types they are, it does obfuscate the code and make it harder for us to help. – krillgar Feb 02 '16 at 12:43
  • 1
    @HimBromBeere He's referring to the OP – DGibbs Feb 02 '16 at 12:46
  • @Tim I now saw which var you mean and changed it, for other "var"s the type is right next to it. – Andreas Reiff Feb 02 '16 at 12:50
  • 1
    Linq is nice to make code simple and readable, it is also recommended by Unity to avoid it when possible and use your own code. "– “Linq” — Examine the time lost to creating and discarding Linq queries; consider replacing hotspots with manually-optimized methods." – Everts Feb 02 '16 at 12:52
  • @AndreasReiff - would it have exhausted you to properly capitalise the question title? – Fattie Feb 02 '16 at 15:39
  • and you should all listen to @fafase – Fattie Feb 02 '16 at 15:40

2 Answers2

8

It must be an IEnumerable<T> in order to get access to the LINQ expressions.

One way to convert from IEnumerable to IEnumerable<T> is to use OfType<T> or Cast<T> extension methods (if you know the type).

e.g.

List<Transform> transforms = transform.Cast<Transform>().ToList();

See also Does LINQ work with IEnumerable

Community
  • 1
  • 1
Dr. Andrew Burnett-Thompson
  • 20,980
  • 8
  • 88
  • 178
4

You can use Enumerable.Cast if Transform doesn't implement IEnumerable<Transform>:

List<Transform> children = transform.Cast<Transform>().ToList(); 

otherwise it's simple as:

List<Transform> children = transform.ToList(); 
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939