JWP
JWP

Reputation: 6963

How do I use a generic method to build a list of same type?

Given:

public static void GetAllTypesInContainer<t>(AContainerWithChildren bw)
{
    var list = new List<t>();       
    var stuff = bw.GetChildren();

    foreach (var child in stuff)
    {
        if (child.GetType().Name == typeOf(t).Name)
        {
            list.Add((t)child);
        }
    }
}

How do I add values of that type to the list?

Upvotes: 1

Views: 87

Answers (2)

Will
Will

Reputation: 2532

If I understand the code, you're trying to get all children of type t into a list, and ignoring the rest. Linq makes that easy. I'm assuming the result of calling bw.GetChildren() is enumerable based on your example.

using System.Linq;
// ...   

private static List<T> GetAllTypesInContainer<T>(this Container bw)
{
    var list = bw.GetChildren().OfType<T>().ToList();
    return list;
}

Or for a version optimised to suit the fluent coding style the OP is after, keeping the context with the container:

private static Container ForEachChildOfType<T>(this Container bw, Action<T> action)
{
    var children = bw.GetChildren().OfType<T>().ToList();

    children.Do(action);

    return bw;
}

// later to be used similar as follows as per OP's example

bw
  .StoreInformation()
  .ForEachChildOfType<HtmlHyperLink>(link =>
  {
      if (link.Href == "Something") // caution, watch for mixed case!!!
      {
      }
  })
  .AssertControlTitleOnHomePage();

NB As a general coding style I'd never call a method GetXXX unless it actually returned something, hence the name change.

ps. Hope there's no typos in there, this is all from memory!

Upvotes: 5

JWP
JWP

Reputation: 6963

The final solution was:

     public static Container GetAllTypesInContainer<t>(this Container bw, Action<List<t>> Callback)
    {
        var list = new List<t>();            
        list= bw.GetChildren().OfType<t>().ToList();
        Callback(list);
        return bw;
    }

The reason for the callbacks is in the design of the FLUID interface for the type Container. Callbacks allow me to return the static method instance type rather than the list, as a result I can chain all the activity and still process the content like this:

 bw
    .StoreInformation()
    .GetAllHtmlHyperLinks((p) =>
    {
        p.ForEach((q) =>
        {
            if (q.Href == "Something")
            {
            }
        });
    })
    .AssertControlTitleOnHomePage();

The callbacks allow me to process the results using anonymous methods.

Upvotes: 0

Related Questions