0

I'm using LINQ to XML/LINQ to Objects to create an object, and the object has a property that is an enum. I'm trying to figure out how to do a switch on a particular string from the XML and set the enum to a specific value.

I've listed below what I've tried so far but I just don't know the actual way to switch on attribute values. What should I do?

Example XML:

<post title="Title" type="newsletter">blah</post>
<post title="Another title" type="email">blah</post>
<post title="etc" type="newsletter">blah</post>

Example model:

public class PostItem
{
    public PostType PostType { get; set; }
}

public enum PostType
{
    EMail,
    Newsletter,
    Rss
}

And this is the actual code for constructing the models:

public IEnumerable<PostItem> GetPosts()
{
    var data = from postItem in xDoc.Descendants("etc etc")
               select new PostItem
               {
                   Title = (string)postItem.Attribute("title"),
                   NewsType = ?

                   //**I'm wanting to do something like this**
                   switch((string)postItem.Attribute("type")
                   {
                       case "newsletter":
                           PostType = PostType.Newsletter;

                       etc.
               };

    return data;
}
user9993
  • 5,833
  • 11
  • 56
  • 117
  • So, you need to write extension method which accept `XElement` as input parameter and returns `PostType`. – Maciej Los Jun 01 '15 at 20:00
  • Question is closed so my answer went poof, but in any case, your issue is the fact that you are in an object initializer. You cannot put a `switch` statement in there. Instead, put your `switch` in a method with a parameter to switch on and then pass in your data. `PostType = ConvertToPostType(postItem.Attribute("type").Value.ToString())` – TyCobb Jun 01 '15 at 20:02

0 Answers0