Can't find property or field on a dynamic object

前端 未结 2 1636
走了就别回头了
走了就别回头了 2021-01-25 17:25

I using Dynamic Linq to do some database queries and it\'s working really well up to now. I can pass a string to a Select to select fields like so:

         


        
2条回答
  •  囚心锁ツ
    2021-01-25 17:51

    If you do YourStuff.Cast.ToList(), you will receive IEnumerable, and there is no property Foo on the type object.

    The question you might be asking, how can you get IList?! You can do it this way:

    // for IEnumerable
    public static IList ToAnonymousList(this IEnumerable enumerable)
    {
        var enumerator = enumerable.GetEnumerator();
        if (!enumerator.MoveNext())
            throw new Exception("?? No elements??");
    
        var value = enumerator.Current;
        var returnList = (IList) typeof (List<>)
            .MakeGenericType(value.GetType())
            .GetConstructor(Type.EmptyTypes)
            .Invoke(null);
    
        returnList.Add(value);
    
        while (enumerator.MoveNext())
            returnList.Add(enumerator.Current);
    
        return returnList;
    }
    
        // for IQueryable
        public static IList ToAnonymousList(this IQueryable source)
        {
            if (source == null) throw new ArgumentNullException("source");
    
            var returnList = (IList) typeof (List<>)
                .MakeGenericType(source.ElementType)
                .GetConstructor(Type.EmptyTypes)
                .Invoke(null);
    
            foreach (var elem in source)
                returnList.Add(elem);
    
            return returnList;
        }
    

    It's a simple extension method that can later be used, as such:

    var test = (new[]
    {
        new
        {
            Property1 = "10",
            Property2 = "10",
            Property3 = 1
        }
    }
    .Select("New(Property1, Property2)"))
    .ToAnonymousList();
    

    提交回复
    热议问题