Populating Objects Using LINQ

I want to understand a little more about LINQ and use it a little more, so a bit of self-development work happens 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 the list of players, I would like to select the ones that previously played for different selected clubs, I could do it easily with a few foreach instructions, but I would like to do it with Linq ...

I tried this, but nothing returns 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 on where I'm wrong? The data definitely exists, because when I have a foreach loop, looping over the clubs inside the loop that loops over the players, and I return a collection of all the players who played in clubs 1,2 and 3, there is data ...

HistoryOfPlayer, 3- ( ) - , , , !!

- ?

+5
1

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) 
                };

svik :

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) 
                };

* , IDE, , .

+4

All Articles