Search

Archiv

Suche

Liste

Blog - Christian Wirth

Jul 27

Written by: Christian Wirth
27.07.2009 00:17 

Mittlerweile habe ich einen ganzen Berg von Extension Methods geschrieben.
Eine welche immer wieder verwende werd ich jetzt mit euch teilen :)

 

   1:          /// <summary>
   2:          /// Flattens a recusrsive structure into one eumarable list
   3:          /// </summary>
   4:          /// <typeparam name="T"></typeparam>
   5:          /// <param name="source">The source.</param>
   6:          /// <param name="childListSelector">The child list selector.</param>
   7:          /// <returns></returns>
   8:          public static IEnumerable<T> FlatOut<T>(
   9:              this IEnumerable<T> source, Func<T, IEnumerable<T>> childListSelector)
  10:          {
  11:              List<T> flattened = new List<T>();
  12:   
  13:              flattened.AddRange(source);
  14:   
  15:              while (flattened.Count > 0)
  16:              {
  17:                  T current = flattened[0];
  18:                  flattened.RemoveAt(0);
  19:   
  20:                  IEnumerable<T> childList = childListSelector(current);
  21:   
  22:                  if (childList != null)
  23:                      flattened.AddRange(childList);
  24:   
  25:                  yield return current;
  26:              }
  27:          }

Damit wird eine rekursive Struktur in eine flache Liste überführt.

Eine nützliche Anwendung in einer weiteren Extension:

   1:   /// <summary>
   2:          /// Flats the out child controls from recursive to list.
   3:          /// </summary>
   4:          /// <param name="c">The c.</param>
   5:          /// <returns></returns>
   6:          public static List<Control> FlatOutChildControls(this Control c)
   7:          {
   8:              return c.Controls.Cast<Control>()
   9:                .FlatOut(c1 => c1.Controls.Cast<Control>())
  10:                .ToList();
  11:          }

Damit bekommt man also ALLE ChildControls eines ASP Controls in einer flachen Liste. Sehr nützlich wenn man mit FindControl nicht weiterkommt...

Tags:

1 comment(s) so far...

Re: FlatOut Extension Method

Hallo Christian

Beide Methoden sind nützlich, allerdings muss ich dir hier wiedersprechen:

> Sehr nützlich wenn man mit FindControl nicht weiterkommt...
Dann nutzt man sowas, wie FindControlRecursive(), das ist intuitiver und vom Aufwand her je nach dem auch kleiner.

-
www.aspnetzone.de/blogs/peterbucher/archive/2009/01/20/findcontrol-mal-anders-iterativ-rekursiv-generisch-mit-bedingungen.aspx

Gruss Peter

By Peter Bucher on   10.08.2009 22:37

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment   Cancel 
Copyright 2007
Datenschutzerkläung   |   Nutzungsbedingungen