[英]How do I check if one list contains 2 elements of another list with more elements?
[英]How do I know if elements from one list appear in another?
我需要知道C#中的一種有效方法,以確定listX中的元素是否出現在listY中。 我可以通過編寫很多循環以(可能)低效率的方式來完成此操作,但我想有一種必須更快的方式(lambda表達式?)
我正在從Java跳到C#,所以很多事情對我來說都是新的。 我正在寫井字游戲,並有7個場景可以贏得游戲。
private int[] scenarioA = {1, 2, 3};
private int[] scenarioB = {4, 5, 6};
private int[] scenarioC = {7, 8, 9};
private int[] scenarioD = {3, 5, 7};
private int[] scenarioE = {1, 4, 7};
private int[] scenarioF = {2, 5, 8};
private int[] scenarioG = {3, 6, 9};
每當玩家按下按鈕時,我都會將單元格的編號保存在clickedCellsO或ClickedCellsX中。 擊中5個單元格后,我需要檢查是否有獲勝者,因此我需要遍歷clickedCellsO或ClickedCellsX以查看其是否具有方案之一的組合。
List<int> clickedCellsO = new List<int>();
List<int> clickedCellsX = new List<int>();
有人可以給我一個建議,而無需使用長凳循環嗎?
提前致謝
您可以只使用LINQ:
var winningConditions = new[] {
scenarioA,
scenarioB,
scenarioC,
// ...
};
var hasPlayerOWon = winningConditions.Any(placements => placements.All(clickedCellsO.Contains));
var hasPlayerXWon = winningConditions.Any(placements => placements.All(clickedCellsX.Contains));
您可以使用List<List<int>>
來存儲獲勝組合,然后檢查使用某些System.Linq
方法來確定玩家的組合是否包含獲勝組合中Any()
項目的All()
。
以下方法中的代碼基本上說: “如果任何獲勝組合中的所有項目都包含在玩家的組合中,則返回true,否則返回false” 。
private static readonly List<List<int>> WinningCombinations = new List<List<int>>
{
new List<int> {1, 2, 3}, new List<int> {1, 5, 9},
new List<int> {1, 4, 7}, new List<int> {2, 5, 8},
new List<int> {3, 5, 7}, new List<int> {3, 6, 9},
new List<int> {4, 5, 6}, new List<int> {7, 8, 9},
};
private static bool IsAWinner(List<int> playerCombination)
{
return WinningCombinations.Any(winningCombo =>
winningCombo.All(playerCombination.Contains));
}
在使用中,您可能會執行以下操作:
if (IsAWinner(clickedCellsX))
{
// Player 'X' wins!
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.