简体   繁体   English

如何在C#中基于属性进行排序

[英]How to do sorting on the basis of attributes in c#

I have below code in c#, where I am trying to generate xml. 我在c#中有以下代码,我正在尝试生成xml。

foreach (Component compCategories in categories)
{
    GenerateXML(xml, compCategories);
}

private void GenerateXML(XmlWriter xml, Component compCategory)
{
    xml.WriteStartElement("category");

    xml.WriteAttributeString("id", compCategory.Id.ItemId.ToString());

string order = compCategory.Title; 字符串顺序= compCategory.Title;

    xml.WriteAttributeString("order", order);
    Component detailCategory = compCategory.ComponentValue("Detail");
    if (detailCategory != null)
    {
        xml.WriteAttributeString("detail", detailCategory.Id.ItemId.ToString());
    }
    Component catArtwork = compCategory.ComponentValue("Artwork");
    if (catArtwork != null)
    {
        Component summaryArtwork = catArtwork.ComponentValue("Summary");
        if (summaryArtwork != null)
        {
            String CatImageUrl = PublishBinary(summaryArtwork);
            xml.WriteAttributeString("image", CatImageUrl);
        }
    }
    xml.WriteElementString("title", compCategory.StringValue("Title").ToString());
    xml.WriteElementString("summary", compCategory.StringValue("Summary").ToString());
    xml.WriteElementString("linktext", compCategory.StringValue("Linktext").ToString());
    xml.WriteEndElement();
}

How can I sorting xml rendering on the basis of "order" (highlighted above) attribute value, I am not going to use XSLT, however LINQ is fine. 如何基于“顺序”(上面突出显示)属性值对xml呈现进行排序,我不会使用XSLT,但是LINQ很好。

Please suggest!! 请建议!

Thanks 谢谢

Could you sort your collection before generating the XML? 您可以在生成XML之前对集合进行排序吗?

var ordered = categories.OrderBy(cat=>cat.Title);
foreach (Component compCategories in ordered)
{
    GenerateXML(xml, compCategories);
}

Sort your list before calling Generatexml() : 在调用Generatexml()之前对列表进行排序:

foreach (Component compCategories in categories.OrderBy(c => c.Title).ToList())
{
    GenerateXML(xml, compCategories);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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