Sparkzi
Sparkzi

Reputation: 83

Linq - Select rows which are on lists

I have got table "Actions" which has fields like Player, Game, Type - ale connected with other tables. I have also two Lists in my c# code:

    List<Player> playersForStats
    List<Game> gamesForStats

Now i want to select a rows from Actions which (field)Players are in list playersForStats and (field)Game are in list gamesForStats. How can I make it using linq? I have to use inner join or something else?

Upvotes: 1

Views: 2667

Answers (3)

Saeed Amiri
Saeed Amiri

Reputation: 22555

I'd assume your action list named as actions:

actions.Where(x=>playersForStats.Contains(x.Player) && gamesForStats.Contains(x=>x.Game));

In fact just need to search if playersForStats and gamesForStats contains related action's player and game.

Upvotes: 1

Steven Muhr
Steven Muhr

Reputation: 3379

Something like this :

class Program
{
    static void Main(string[] args)
    {
        List<Action> actions = new List<Action>();
        List<Game> gamesForStats = new List<Game>();
        List<Player> playersForStats = new List<Player>();

        List<Action> result = (from oAction in actions
                               join game in gamesForStats on oAction.Game equals game.GameName
                               join player in playersForStats on oAction.Player equals player.PlayerName
                               select oAction).ToList();

        Console.ReadLine();
    }
}

public class Player
{
    public string PlayerName { get; set; }
}

public class Game
{
    public string GameName { get; set; }
}

public class Action
{
    public string Player { get; set; }
    public string Game { get; set; }
    public string Type { get; set; }
}

Upvotes: 0

Kamil Lach
Kamil Lach

Reputation: 4629

Something like this should work if your object has proper equals method:

var oActions = ..
var oData = oActions.Where(c=> c.Players.TrueForAll(p => playersForStats.Contains(p)) && gamesForStats.Contains(c.Game));

Assuming that c.Players is List And c.Game is Field.

Upvotes: 2

Related Questions