简体   繁体   中英

C# select data into the viewmodel using linq

I have a viewmodel

    public class CompanyDetailVM {
      public string CompanyName { get; set; }
      public IEnumerable<Comments> Comments { get; set; }
   }

I want to retrieve all the data coming from XML, I cant figure out how to get list of comments too (Comments model consist of CommentText, DateTaken). My code looks like:

   var model= new CompanyDetailVM
   {
       CompanyName = detail.Element("result").Element("name").Value,
       Comments = new Models.Comments {  
                CommentText=  detail.Element("result").Element("comment").Element("text"),
                DateTaken = detail.Element("result").Element("comment").Element("date")
       }
   }

Error: Cannot implicitly convert type 'Models.Comments' to 'System.Collections.Generic.IEnumerable

I also dont think doing new Models.Comments is the right way. How do I fix the code correctly?

If you just have a single Comment in your XML - as it looks like you do here - then the easiest is to do:

var model= new CompanyDetailVM
{
    CompanyName = detail.Element("result").Element("name").Value,
    Comments = new [] { 
        new Models.Comments {  
            CommentText=  detail.Element("result").Element("comment").Element("text"),
            DateTaken = detail.Element("result").Element("comment").Element("date")
        }
    }
 }

(Note the shorthand array literal syntax - new [] { ... } for easily creating an array (which of course implements IEnumerable<> ))

If your XML may contain multiple comments, eg

<result>
    <name>Test</name>
    <comment><text>One</text>...</comment>
    <comment><text>Two</text>...</comment>
</result>

Then you might want to move towards using LinqToXML to transform all <comment> tags into Models.Comments objects.

Currently, you assigned a Models.Comment object to a property expecting IEnumerable<Comments> type, which then trigger that conversion error. You can create IEnumerable<Comments> from XML using LINQ like so :

var model= new CompanyDetailVM
{
   CompanyName = detail.Element("result").Element("name").Value,
   Comments = from comment in detail.Element("result").Elements("comment")
              select new Models.Comments 
                     {
                        CommentText = (string)comment.Element("text"),
                        DateTaken = (DateTime)comment.Element("date")
                     }
}

Notice that I use Elements("comment") (with plural Elements ) assuming that you may have multiple <comment> elements in the XML source.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM