c# - Linq every occurrence of value, bind to ViewModel -


i need list of players , every team said player associated , add viewmodel.

viewmodel

public class playersviewmodel {     public long playerid { get; set; }     public string playername { get; set; }     public list<long> teamid { get; set; } //players can assigned 1 or more teams } 

i have few different datatables going on:

  • playersinteams (linking table)
+------------+---------+ |  playerid  | teamid  | +------------+---------+ | 1          | 10001   | | 1          | 10002   | | 2          | 10002   | | 3          | 10001   | +------------+---------+ 
  • players
+------------+---------+-----------+ |  playerid  | forename| surname   | +------------+---------+-----------+ | 1          | john    |  doe      | | 2          | pete    |  noe      | | 3          | evan    |  soe      | +------------+---------+-----------+ 

so above example tables, player 1 - john doe should have array of 2 teamids in viewmodel [10001, 10002].

aim

i'm trying have list<playersviewmodel> collection of teamids.

code

public list<playersviewmodel> getplayers() {     var playersinteam = new playersinteamsbll();      var pit = playersinteam.getplayersinteams();      var playerdetail = players;      var list = p in pit         join team in teams on p.teamid equals team.teamid // teams related club         join pd in playerdetail on p.playerid equals pd.playerid //link player          pd.isarchived == false         select new playersviewmodel { teamid  = team.teamid, playerid = p.playerid, playername = pd.forename + " " + pd.surname};      return list.tolist(); } 

i'm getting null playerids , teamid isn't getting populated.

any suggestions / solutions?

try this:

var viewmodels = playerdetail.select(p => new playersviewmodel() {   playerid = p.playerid,   playername = string.format("{0} {1}", p.forename, p.surname),   teamid = pid.where(pidelement => pidelement.playerid == p.playerid)               .select(pidelement => pidelement.teamid).tolist() }).tolist(); 

in general seems me you're trying tackle problem wrong end. want list of players first, , teams second, not list of player-team associations first, , player details second, should start playerdetail object (i assume it's ienumerable of player objects).

on side note: consider can add getter player class give full name without need concatenate name , surname. like:

public string fullname {   { return string.format("{0} {1}", this.firstname, this.surname); } } 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -