How to merge similar IList<T> objects in C# asp.net MVC
I have a class:
public class Data {
public Ilist<Prod> Product;
public Data() {}
public Data(List<Prod> prod)
{
this.Product = prod
}
}
No I try to use this class in my controller to bind values to my model
public ActionResult Index(string username)
{
data.Prod = GetProductByUser(username); // this is the base user
IList<AdditionalUsers> add_usrs = GetAddUsersForBaseUsers(username);
// now to the data.prod (product list I need to add the prod for the base users
//so I loop through the add users and try to get the products for each base use
for(AdditionalUsers aid in add_usrs)
{
//now data.prod has products for base users. So now I need to add produts
//for add users using same method
}
}
Now in the for loop I need to call the same method GetAddUsersForBaseUsers(username); to add product for all the additional users and add it to the data.Product 开发者_Python百科list. How will I be able to do this?
You can use the Concat function, like this:
List<int> lst = new List<int>();
List<int> lst2 = new List<int>();
List<int> lst3 = new List<int>();
lst.Concat(lst2).Concat(lst3);
Ok, your constructor is wrong. You're trying to set data.Prop where Prop is a type, not a public field/property. Also, where are you declaring your data variable?
You could use the following instead:
Data data = new Data(GetProductByUser(username));
Make your Product field as a publicly accessible property as well.
To do this, replace
public Ilist<Prod> Product;
with public IList<Prod> Product { get; set;}
To Add the users, you can use the following.
foreach(AdditionalUsers aid in add_usrs)
{
//add users
data.Product.Add(aid);
}
Alternatively you can just replace the property Product which is of type IList
with a List
and then do the following:
data.Product.AddRange(add_usrs);
data.Prod = GetProductByUser(username);
IList<AdditionalUsers> add_usrs = GetAddUsersForBaseUsers(username);
List<List<Prod>> productsForAdditional = new List<List<Prod>>();
foreach(AdditionalUsers aid in add_usrs)
{
//get all of those lists.
productsForAdditional.Add(GetProductByUser(aid.UserName);
}
//add all of the items from all of those lists to the primary list
data.Prod.AddRange(productsForAdditional.SelectMany(list => list));
精彩评论