Populate a list property from delimited string

2019-08-11 15:23发布

问题:

This is kind of a simple application but I'm a bit new to ASP.NET MVC so I'm having a bit of trouble wrapping my head around how to accomplish this because the

What I have are two classes:

public class BugAssignment
{
    public int BugAssignmentID { get; set; }
    public int BugNumber { get; set; }
    public int UserID { get; set; }
    public virtual User User { get; set; }
}

public class BugAssignmentList
{
    public int BugAssignmentListID { get; set; }
    public string Name { get; set; }
    public List<BugAssignment> BugAssignments { get; set; }
}

What I want do is populate the List of BugAssignments given user inputted delimited string of BugNumbers from (i.e. 208,576,403). I'm guessing it would explode the string, loop through and create the BugAssignment objects, store into a list and set the BugAssignments property. How could I accomplish this?

Also, I am using Entity Framework Code-first with SQL server 2008 as my database engine.

回答1:

If you're stuck on converting the string to an array of strings...

Splitting a comma separated string into an Array of string objects is fairly straightforward using String.Split() in C#.

string[] StringArray = String.Split(BugAssignments , ",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

From there, it should be straightforward to loop through the array and do the remainder of the work. If you're stuck on a different part, let us know.



回答2:

Using string.Split, and the Linq Select, here's how you could write it:

string BugNumbers = "208,576,403";
int currentUserID = 0;

BugAssignmentList list = new BugAssignmentList
{
    BugAssignments = BugNumbers.Split(',')

        // convert list of numbers to list of BugAssignment objects
        .Select(num => new BugAssignment 
        { 
            BugNumber = int.Parse(num.Trim()),
            UserID = currentUserID 
        })
        .ToList(),
    Name = "assignment list name"
};