Convert Anonymous Type to Class

Convert anonymous type to class

Well, you could use:

var list = anBook.Select(x => new ClearBook {
Code = x.Code, Book = x.Book}).ToList();

but no, there is no direct conversion support. Obviously you'll need to add accessors, etc. (don't make the fields public) - I'd guess:

public int Code { get; set; }
public string Book { get; set; }

Of course, the other option is to start with the data how you want it:

var list = new List<ClearBook> {
new ClearBook { Code=10, Book="Harry Potter" },
new ClearBook { Code=11, Book="James Bond" }
};

There are also things you could do to map the data with reflection (perhaps using an Expression to compile and cache the strategy), but it probably isn't worth it.

How to convert Anonymous Type to Strong Type from LINQ query

You can create strongly typed objects in the select:

List<UserTransactionReport> result = 
...
.Select(x => new UserTransactionReport
{
UserId = x.Key.UserId,
ProjectId = x.Key.ProjectId,
CreateTime = x.Key.CreateTime,
TotalMinutesSpent = x.Sum(z => z.MinutesSpent)
}).ToList();

cast list of anonymous type to list of object

Here are the ways possible:

  1. Return a List<object>, which means you have no intellisense on the receiving end
  2. Return a List<dynamic>, which means you have no intellisense on the receiving end, but perhaps easier to access members you know are there than through reflection
  3. Return a List<T> but then you will have to provide an example of how T is supposed to look and this won't be any more safe at runtime than dynamic is
  4. Return a tuple of the new type that came with C# 7

Point 1 and 2 can be easily solved by just ensuring the list is of that type:

...
}.ToList<object>();

Point 3 is a hack but I'll post it below.

Point 4 can be solved with this syntax:

public List<(int Number, string Name)> GetData()
{

var list = new[]
{
(Number: 10, Name: "Smith"),
(Number: 10, Name: "John")
}.ToList();

return list;
}

This will give you intellisense for a while but the naming of the properties is a hack by the compiler and if you start passing these values around they will easily fall back to .Item1 and .Item2.


To cast an object to a specific type you can use a hack which only works in the same assembly that the anonymous object was created in, and that is that multiple anonymous types used around in your code, which has the same properties, in the same order, with the same property types, all end up being the same anonymous type.

You can thus cast an object to a specific anonymous type with this hackish code:

public T AnonymousCast<T>(object value, T example) => (T)value;
public IEnumerable<T> AnonymousCastAll<T>(IEnumerable<object> collection, T example) => collection.OfType<T>();

You would use it in your case like this:

var d = AnonymousCast(GetData()[0], new { Number = 0, Name = "" });

This is no more safe than using dynamic as there is no guarantee the object returned from GetData actually is of that anonymous type.

In short, use a named type.

how to convert anonymous type to known type

You can't use casting here, because neither you anonymous type inherited from MyClass nor you have explicit type conversion operator defined for these types.

You can use AutoMapper (available from NuGet) to dynamically map between anonymous type and your class

var a = new {property1 = "abc", property2 = "def"};
Myclass b = Mapper.DynamicMap<Myclass>(a);

It maps properties of anonymous object to properties of destination type by name:

enter image description here

How can I convert Anonymous type to Ttype?

The only type that you can cast an anonymous type to is Object. If you want any other type, you have to create those objects from the data in the anonymously typed objects.

Example:

List<MyType> items = aType.Select(t => new MyType(t.Some, t.Other)).ToList();

You should consider to create the MyType objects already when you get the data, instead of creating anonymously typed objects.

Trying to convert an C# anonymous type to a strong type

C# is a statically typed language, and those two types are not in any way related to one another. Unless you're able to modify the code which defines those types, the way you'd convert from one to the other would be to create a new instance of the target type and populate it from the source object.

For example:

var resultCat = new Cat { Id = result.Id };

Edit: From comments it looks like it may be possible that the Id property on the result object may be an instance of Cat or some other object? You're going to need to do some debugging to find out what your types are.

But the overall concept doesn't really change. If you have an instance of Cat in your results then you can use that instance. If you don't then in order to create one you'd need to create a new instance and populate it with the data you have. Even if two types are intuitively or semantically similar, they are different types.

Convert a List of Anonymous type to a list of a specific Class type

You can try something like this:

public static class EmployeeExtentions
{
public static List<Employee> FireEmployees(this List<Employee> AllCitiesEmps)
{
List<Employee> employees = new List<Employee>();

using (var ctx = new hr_employeeEntities())
{
var emp = (from x in ctx.F_Emp
join y in ctx.HR_EMPL on (x.employee_id).ToString() equals y.EMPLID
where x.employment_status == "A"
select new
{
x.employee_id,
x.employment_status,
//x.OtherProperties
y.EMPLID,
//y.OtherProperties
}).ToList();

employees = emp.Select(x => (new EmployeeDerived { EmployeeId = x.employee_id, EmploymentStatus = x.employment_status }) as Employee).ToList();

}
return employees;
}

private class EmployeeDerived : Employee
{

}
}

Please note, you will need to create a new derived type though, as you can't directly cast to an abstract type.

Generating classes from Anonymous types in C#

That's one of the refactorings supported by Resharper. With nested anonymous types (where one anonymous type has properties of another anonymous type), you'll just have to convert the inner types before you get the option to convert the outer one.



Related Topics



Leave a reply



Submit