使用Linq检查布尔表达式是否为true

时间:2015-02-09 23:33:26

标签: c# linq

我想使用linq来检查多个逻辑语句中的一个是否返回true。

到目前为止,我已尝试过以下方法:

winningCombinations = new[,] 
    {
        {1,2,3},
        {4,5,6},
        {7,8,9},
        {1,4,7},
        {1,4,7},
        {3,6,9},
        {1,5,9},
        {3,5,7}
    };
if (Enumerable.Range(0,7).Where(x => this.contentOf(winningCombinations[x,0]) == this.contentOf(winningCombinations[x,1]) && 
                                     this.contentOf(winningCombinations[x,1]) == this.contentOf(winningCombinations[x,2]))
                                     .Select(x => true).FirstOrDefault(x => x))
    {
        _isDone = true;
        _game.wonBy(_turnOf);
    }

基本上,contentOf()需要将Index作为参数并返回char值。 我的问题是,有没有办法让我的代码工作?我想使用" winnerCombinations"中包含的坐标。检查我的网格上是否有winCombination(3个相同的字符),最好使用Linq。

1 个答案:

答案 0 :(得分:0)

我很不清楚你正在尝试什么,但听起来就像IEnumerable.Any应该做你想要的。

if (Enumerable.Range(0,7)
              .Any(x => this.contentOf(winningCombinations[x,0]) == this.contentOf(winningCombinations[x,1]) && 
                        this.contentOf(winningCombinations[x,1]) == this.contentOf(winningCombinations[x,2]))
{
    _isDone = true;
    _game.wonBy(_turnOf);
}

这是非常不言自明的,但基本上我们的目标是找到任何集合,其结果为真。如果找到一个,则返回true并跳转到if块。如果它查看整个数组并且找不到任何匹配项,则会返回false


如果您正在寻找更多的LINQ,而且不是,那么可以说是更清洁。可以说

if (Enumerable.Range(0, winningCombinations.GetLength(0))
              .Select(c => Enumerable.Range(0, winningCombinations.GetLength(1)
                                     .Select(x => this.contentOf(winningCombinations[c, x])
              .Any(x => !x.Distinct().Skip(1).Any())
{
    _isDone = true;
    _game.wonBy(_turnOf);
}

分手了,

// Get the indexes for of the array
var ys = Enumerable.Range(0, winningCombinations.GetLength(0));
var xs = Enumerable.Range(0, winningCombinations.GetLength(1));

// Select the values at each index, becomes a collection of collections
var vals = ys.Select(y => xs.Select(x => this.contentOf(winningCombinations[y, x]));

// Discover whether at least one of the sets has exactly one value contained.
return vals.Any(c => !x.Distinct().Skip(1).Any())
相关问题