Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object population with LINQ

Tags:

c#

linq

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?

like image 714
Chris Avatar asked Oct 07 '22 23:10

Chris


1 Answers

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.

like image 136
Frederiek Avatar answered Oct 25 '22 18:10

Frederiek