In my Controller Constructor I initialise my IEnumerable list which I will be passing it as model to my Views.
IEnumerable<classB> mdata;
public MyController()
{
DataContext context = new DataContext(//connectionstring code missing//);
mdata = context.GetTable<classB>().ToArray();
}
In my Action now I want to "add" a column to the mdata from a var list I retrieve from a Session as below:
var list = (List<Tuple<int,int>>)Session["ids"];
The list above contains id & Level both type int. The "id" will be used to match the rows in mdata which also have column "id". So once it finds a match it should add "Level" to the IEnumerable list. So far I have:
mdata = mdata.Where(x => list[].Item1.Contains(x.Id)); //not working
You cannot change your ClassB definition (add/remove properties at runtime) - Level property should exist there. But you can join both sequences by id and then select new anonymous object which will have level and joined ClassB instance:
var query = from b in mdata
join t in list on b.Id equals t.Item1
select new {
B = b,
Level = t.Item2
};
Updating Level
property in ClassB:
foreach(var pair in query)
pair.B.Level = pair.Level;
Another option (you will avoid anonymous objects creation):
var levels = list.ToDictionary(t => t.Item1, t => t.Item2);
foreach(var b in mdata)
{
int level;
if (levels.TryGetValue(b.Id, out level))
b.Level = level;
}
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.