Anonymous type return

I use the trick to return an anonymous type, but I'm not sure if it will work in all scenarios. If there is any problem using this trick, plz let me know so that I will not use this code in my project

class A
{
    public int ID { get; set; }
    public string Name { get; set; }
}

class B
{
    public int AID { get; set; }
    public string Address { get; set; }
}

private List<object> GetJoin()
{
    var query = from a in objA
                join b in objB
                on a.ID equals b.AID
                select new { a.ID, a.Name, b.Address };
    List<object> lst = new List<object>();
    foreach (var item in query)
    {
        object obj = new { ID = item.ID, Name = item.Name, Address = item.Address };
        lst.Add(obj);
    }
    return lst;
}
T Cast<T>(object obj, T type)
{
    return (T)obj;
}

//call Anonymous Type function
foreach (var o in GetJoin())
{
    var typed = Cast(o, new { ID = 0, Name = "", Address = "" });
    int i = 0;
}
+3
source share
2 answers

Yes, it is guaranteed to work as long as everything is within the same assembly. If you cross the assembly boundary, it will not work, although the anonymous types are internal and the โ€œidentificationโ€ is based on:

  • Assembly used in
  • Properties:
    • Name
    • A type
    • Order

Everything must be correct so that the types are considered the same.

It is unpleasant. On the one hand, your GetJoin method can be simplified to:

return (from a in objA
        join b in objB
        on a.ID equals b.AID
        select (object) new { a.ID, a.Name, b.Address })
       .ToList();

... , , .

, . , , , , ... : (

+11

. , .

:

  • . ()
0

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


All Articles