Generic method to map objects of different types

前端 未结 3 1546
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 09:30

I would like to write Generic Method that would map List to new list, similar to JS\'s map method. I would then use this method like this:

var words= new Lis         


        
3条回答
  •  深忆病人
    2021-01-14 09:38

    Linq's Select is the equivalent of the map() function in other functional languages. The mapping function would typically not be called Predicate, IMO - predicate would be a filter which could reduce the collection.

    You can certainly wrap an extension method which would apply a projection to map input to output (either of which could be be anonymous types):

    public static IEnumerable Map(this IEnumerable seznam, 
                                              Func mapper)
    {
        foreach (var item in seznam)
            yield return mapper(item);
    }
    

    Which is equivalent to

    public static IEnumerable Map(this IEnumerable seznam, 
                                              Func mapper)
    {
        return seznam.Select(mapper);
    }
    

    And if you don't want a strong return type, you can leave the output type as object

    public static IEnumerable Map(this IEnumerable seznam, Func mapper)
    {
       // Same implementation as above
    
    
    

    And called like so:

    var words = new List() { "Kočnica", "druga beseda", "tretja", "izbirni", "vodno bitje" };
    var wordsMapped = words.Map(el => new { cela = el, končnica = el.Končnica(5) });
    

    Edit
    If you enjoy the runtime thrills of dynamic languages, you could also use dynamic in place of object.

    But using dynamic like this so this precludes the using the sugar of extension methods like Končnica - Končnica would either need to be a method on all of the types utilized, or be invoked explicitly, e.g.

    static class MyExtensions
    {
        public static int Končnica(this int i, int someInt)
        {
            return i;
        }
    
        public static Foo Končnica(this Foo f, int someInt)
        {
            return f;
        }
    
        public static string Končnica(this string s, int someInt)
        {
            return s;
        }
    }
    

    And then, provided all items in your input implemented Končnica you could invoke:

    var things = new List
    { 
       "Kočnica", "druga beseda", 
        53, 
        new Foo() 
    };
    
    var mappedThings = things.Map(el => new 
    { 
         cela = el, 
         končnica = MyExtensions.Končnica(el, 5) 
         // Or el.Končnica(5) IFF it is a method on all types, else run time errors ...
    })
    .ToList();
    
        

    提交回复
    热议问题