Wednesday, April 1, 2015

What is the technology here(IEnumerable)?

I know the linq codeis for loop over a query.



IEnumerable<int> result = from value in Enumerable.Range(0, 2)
select value;

Also I know how to implement the IEnumerable<T> interface below.



// A custom class that implements IEnumerable(T). When you implement IEnumerable(T),
// you must also implement IEnumerable and IEnumerator(T).
public class StreamReaderEnumerable : IEnumerable<string>
{

private string _filePath;
public StreamReaderEnumerable(string filePath)
{
_filePath = filePath;
}


// Must implement GetEnumerator, which returns a new StreamReaderEnumerator.
public IEnumerator<string> GetEnumerator()
{
return new StreamReaderEnumerator(_filePath);
}

// Must also implement IEnumerable.GetEnumerator, but implement as a private method.
private IEnumerator GetEnumerator1()
{
return this.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator1();
}

}

Now I have the code below.



static class Program
{
static void Main()
{
var obj = new object();
int count = AllParents(obj).Count(); // Using Linq only here.
Console.WriteLine(count);
}

public static IEnumerable<object> AllParents(object obj)
{
while (true)
{
obj = GetParentObject(obj);

if (obj == null)
yield break;

yield return obj;
}
}

// This is merely a hacky test implementation.
public static object GetParentObject(object obj)
{
if (--count == 0)
return null;

return obj;
}

private static int count = 10;
}

I don't know what is the best term to describe the method.

public static IEnumerable<object> AllParents(object obj){ blah blah}


No comments:

Post a Comment