I'm looking to understand a bit more about LINQ and use it a little more, so a little bit of self development work going here...
I have an object as follows:
public class Player(){
public string Name{get;set;}
public Club currentClub{get;set;}
public IEnumerable<Club> previousClubs{get;set;}
}
Now, given a list of players, I'd like to select the ones that have formerly played for various selected clubs, I could do it easily by a couple of foreach statements nested - but I'd like to do it with Linq...
I've tried this, but nothing is returned from it:
var prevClubs =
from player in players
from clubOriginal in player.previousClubs
from clubSecond in player.previousClubs
from clubThird in player.previousClubs
where clubOriginal.ID == 1
where clubSecond.ID == 2
where clubThird.ID == 3
select new HistoryOfPlayer{
firstClub == clubOriginal.Name,
secondClub == clubSecond.Name,
thirdClub == clubThird.Name
}
Any help in where I'm going wrong? The data definitely exists because when I have a foreach loop looping over the clubs inside a loop which loops over the players and I return a collection of all players who've played for clubs 1,2 & 3 there is data...
Effectively it should return several instances of a HistoryOfPlayer object, all containing the names of the same 3 clubs (given they're linked on ID) - as I say, its a bit of self learning, so trying to apply it to sport so it sticks in my head a bit!!
Can someone help out?
you could make it more dynamic
List<int> clubIds = new List<int> { 1, 2, 3};
var prevClubs = from player in players
where player.previousClubs.Any(m => clubIds.Contains(m.ID))
select new HistoryOfPlayer {
Player = player,
Clubs = player.previousClubs
.Where(m => clubIds.Contains(m.ID))
.Select(c => c.Name)
};
edit after svik his remarks:
List<int> clubIds = new List<int> { 1, 2, 3};
var prevClubs = from player in players
where clubIds.All(id => player.previousClubs
.select(club => club.ID)
.contains(id))
select new HistoryOfPlayer {
Player = player,
Clubs = player.previousClubs
.Where(m => clubIds.Contains(m.ID))
.Select(c => c.Name)
};
*Note this is written without a IDE, so i haven't checked if it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With