1 Replies - 2207 Views - Last Post: 26 January 2016 - 03:22 AM

#1 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon

Reputation: 2298
  • View blog
  • Posts: 9,535
  • Joined: 29-May 08

Aggregate (Ext Meth)

Posted 27 December 2011 - 02:18 PM

Description: An aggregate function that also indicate the index position of the element.

  static R Aggregate<T,R>(this IEnumerable<T> source, Func<R,int,T, R> f)
  { 
    var i=0;
    R result= default(R);
    foreach( T e  in source)
    {
      result=f(result,i,e);
      i++;
    }
    return result ; 
  }

Is This A Good Question/Topic? 0
  • +

Replies To: Aggregate (Ext Meth)

#2 andrewsw  Icon User is offline

  • lashings of ginger beer
  • member icon

Reputation: 6340
  • View blog
  • Posts: 25,569
  • Joined: 12-December 12

Re: Aggregate (Ext Meth)

Posted 26 January 2016 - 03:22 AM

Here is an example usage that takes a list of strings and joins the 1st letter from the first word, the 2nd letter from the second word, etc..
namespace ExtensionMethods {

    public class Program {
        public static Func<string, int, string, string> OffsetChars = (x, i, y) => {
            return x + y[i];
        };

        static void Main(string[] args) {
            List<string> test = new List<string>() { "hello", "there", "you" };
            // get h from (h)ello, h from t(h)ere and u from yo(u) (hhu)
            string result = test.MyAggregate(OffsetChars);
            Console.WriteLine(result);

            Console.ReadKey();
        }
    }
}

(which was discussed a little bit here)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1