locked
Unable to typecast AnonymousType1'2[String, Int] to Models.BookmarkTag [Crucial] -- RRS feed

  • Question

  • User-215451226 posted

    This is the problem scenario -

    In my app. I am doing some query and deriving results. Then trying to cast/convert them into a specific object type called
    BookmarkTag.

    Code for generating results -

    var bkTags = (
                               from p in keyWords
                               select new
                               {
                                   p.Key,
                                   p.Value
                               }).Cast<BookmarkTag>().AsEnumerable();

    BookmarkTag.cs class -

    public class BookmarkTag
        {
            public string Key { get; set; }
    
            public int Value { get; set; }
        }

    Another variant I tried -

    var bkTags={
                  from p in keyWords
    		      select new BookmarkTag()
    			  {
    			     p.Key,    // throws error in these 2 lines, BookmarkTag class does not implement IEnumerable
    				 p.Value
    			  }).AsEnumerable(); 

    Here keyWords is a variable that contains data in form as -- refer the attached pic link -->  pasteboard.co/JEsf72I.png
    Error I am getting -

    Unable to cast object of type '<>f__AnonymousType1`2[System.String, System.Int32]' to type 'WordCloud.Web.Models.BookmarkTag'.

    My 1st guess, BookmarkTag class requires Id field also, since result set is like a List of values and each key-value pair has an index also like {0}, {1}, {2} ..... but, unlikely. 

    What's the fix? Modification in BookmarkTag model class or query used? Any direct lambda expr. available for achieving the same?

    Friday, December 11, 2020 4:59 PM

Answers