ARH
ARH

Reputation: 1716

linq to class of T

I have below:

var attributes = from root in doc.Elements()
                 where root.Name == "quran"
                 from suras in root.Elements()
                 where suras.Name == "suras"
                 from sura in suras.Elements()
                 where sura.Name == "sura"
                 from atts in sura.Attributes()
                 select atts;

List<Sura> item = new List<Sura>();

and Class

public class Sura
{
    private string _aya;
    private string _ayaTranslation;
    System.Windows.HorizontalAlignment _ayaAlignment;
    public string Aya
    {
        get { return _aya; }
        set { _aya = value; }
    }
    public string AyaTranslation
    {
        get { return _ayaTranslation; }
        set { _ayaTranslation = value; }
    }
}

below is the XML

<quran>
  <suras>
    <sura Aya="123" AyaTranslation="321"></sura>
    <sura Aya="123" AyaTranslation="321"></sura>
    <sura Aya="123" AyaTranslation="321"></sura>
  </suras>
</quran>

I want to convert "att" to list "item", But I have no idea how do it. Though I googled, but doesn't help.

Upvotes: 0

Views: 81

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

You don't actually need attributes list, you can get List<Sura> directly from your document.

var items = (from sura in doc.Root.Element("suras").Elements("sura")
             select new Sura {
                  Aya = (string)sura.Attribute("Aya"),
                  AyaTranslation = (string)sura.Attribute("AyaTranslation")
             }).ToList();

As you can see, I removed couple from/where from your query. If you only expect one element with given name it's easier to use Element("name"). And you can always get document root element from Root property.

Upvotes: 1

Related Questions