简体   繁体   中英

Is there a way to conditionally serialize C# list objects based on a property?

I have an MVC Model that generates JSON files, based off of user inputs, that are used as part of an automated workflow. The issue that I am having is figuring out how to change the order in which a list of objects are serialized based off of a specific property value.

Here is a simplified look at my model:

public class Ticket
{
    public string TicketNumber { get; set; }
    public string TicketName { get; set; }
    public string ApplicationName { get; set; }
    public IList<Jams> JamsList { get; set; }
}

public class RootObject
{
    public Ticket ChangeTicket { get; set; }
}

public class JamsDestination
{
    public string Dev { get; set; }
    public string QA { get; set; }
    public string Prod { get; set; }
}

public class Jams
{
    public string TFSLocation { get; set; }       
    public string FileName { get; set; }
    public string JamsType { get; set; }
    public JamsDestination JamsLocation { get; set; }
}

(I am using Newtonsoft.Json and the SerializeObject() function in the post section of my controller)

JamsType is a drop down list populated from a sql table (Variable, Job, Trigger, and Box). What I am trying to do is ensure that any Jams change (in the list: JamsList) is serialized in an order that ensures that all Jams changes of JamsType = Box are serialized last , in order to ensure that it will run properly as a part of our automated workflow. Is there any way to accomplish this without setting up some form of Javascript function in the view to reorder them before they are indexed? (My view is a dynamic table setup so it is not guaranteed that there even will be any Jams changes each time, let alone how many are associated with a ticket).

I realized that I just needed to add Linq logic into my controller PRIOR to serializing the JSON file by doing the following:

ticket.JamsList = ticket.JamsList.OrderBy(jams => jams.JamsType == "Box").ToList();

All this actually does is just reorder the list of Jams changes to meet my conditions before it gets serialized, rather than changing the order it serializes the list (how I thought it needed to be performed).

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