markzzz
markzzz

Reputation: 47945

How can I extend a custom LINQ operation?

I have a list of:

IList<MyObject> myList = new List<MyObject>();

and I'd like to create an exstension which take the list, and union some object. Such as

mylist = myList.AddCustomObjects();

which take myList and UNION it with another List<MyObject> generete on the fly on AddCustomObjects().

How can I do it?

Upvotes: 2

Views: 122

Answers (2)

Christos
Christos

Reputation: 53958

You could use an extension method, in order to achieve this. However, since the functionality you want exists for types that implement IEnumerable, like yours, I don't see the reason why you want to declare a new extension method.

static class Extensions
{
    public static void AddCustomObjects<T>(this List<T> source, List<T> list)
    {
        if(source!=null && list!=null)
            source.AddRange(list);
    }
}

Upvotes: 3

ashish
ashish

Reputation: 245

You can do it by following way:

 public class person
    {
        public string name { get; set; }
        public int age { get; set; }
    }

===================================================================

 public static class ListExtensions
    {
        public static List<T> AddObject<T>(this List<T> lst)
        {
            var a = default(T);
            lst.Add(a);
            return lst;
        }
    }

===================================================================

 List<person> p = new List<person>();
            var result= p.AddObject();

Let me know in case u need any more update!

Ashish

Upvotes: 0

Related Questions