Can't find property or field on a dynamic object

前端 未结 2 1639
走了就别回头了
走了就别回头了 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:48

    Your Cast is Defaulting to which will cause an error

    (output as System.Collections.Generics.IEnumerable)
    

    This Cast Specified the Correct Interface Try again

    (output as System.Collections.IEnumerable).Cast<dynamic>().ToList()
    
    0 讨论(0)
  • 2021-01-25 17:51

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

    The question you might be asking, how can you get IList<TheActualType>?! 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();
    
    0 讨论(0)
提交回复
热议问题