Selecting a new object as a parameter while saving its type created at runtime

Consider the following:

// select a subset of the DataTable
var subset = DataTable.Where(...).Select(row => new
{
    Id = Convert.ToInt32(row["Id"]),
    Name = row["Name"].ToString(),
    Email = row["Email"].ToString()
});

// or create a new object
var subset = new {
    Id = 1,
    Name = "something random",
    Email = "name@domain.tld"
};

Is there a way to use a subset variable as a parameter for a method, without it being presented as simple Object? Can you somehow transfer the automatically generated type of a variable?

I try to avoid having to create new classes every time I want to pass LINQ subsets to methods.

Welcome random generic approaches.

+3
source share
5 answers

Here's what I came up with ... An



object extension method:

public static class ObjectExtensions
{
    /// <summary>
    /// Cast Object to anonymous type.
    /// E.G.: new Object().ToAnonymousType(new { Property = new Type() });
    /// </summary>
    public static T ToAnonymousType<T>(this Object o, T t)
    {
        return (T)o;
    }
}

Using:

public void HandleAnonymousTypeAsParameter(Object o)
{
    var anonymousType = o.ToAnonymousType(new
    {
        Id = new Int32(),
        Foo = new String(),
        Bar = new String()
    });


    // ... You can do this in even less characters:
    var anonymousType = o.ToAnonymousType(new { Id = 0, Foo = "", Bar = "" });
}


HandleAnonymousTypeAsParameter(new
{
    Id = 1,
    Foo = "foo",
    Bar = "bar"
});


The loans are owned by John Skeet and Thomas P.

0

, , *. .

var subset = DataTable.Where(...).Select(row => new SomeType
{
    Id = Convert.ToInt32(row["Id"]),
    Name = row["Name"].ToString(),
    Email = row["Email"].ToString()
});

Tuple, .NET 4. "" .


* , , .

+2

, " ". , API, - . (, ) , ..

, struct ( ).

- - .. Action<int,string,string> callback - - :

foreach(item in query) callback(item);

, , :

DoSomething(args, (id, email, name) => Email(To: email, Subject: name));

( , (id, name, email), , )

+2

:

public static void Foo<T>(T item)
{
    // Do whatever
}

,

Foo(subset);

T . , ... , . , Foo Id, Name, Email ..

, , . - , , , , LINQ.

# 5, , , (, , -, ToString), . , ...

+1
source

Anonymous types do not provide much help outside the context that they created.

If you need to pass an Anonymous type to a method, this method is very general (Example)

void PrintAllObjectProperties(object obj);

After all, you will use reflection to do the work, or you are doing something wrong.

0
source

Source: https://habr.com/ru/post/1759083/


All Articles