是否可以在一行代码中使用一个LINQ

时间:2014-03-15 22:18:52

标签: c# .net linq

在下面的方法中,我想返回所选卡片的索引数组:

public class Card
{
    public bool Selected { get; set; }

    // ... other members here ...
}

public void int[] GetSelectedCards(Cards[] cards)
{ 
    // return cards.Where(c => c.Selected).ToArray();   

    // above line is not what I want, I need their indices
}

有没有人知道一行很好的LINQ代码?可能的?

更新:

有趣的是,我发现了一些东西:

return cards.Where(c => c.Selected).Select(c => Array.IndexOf(cards, c));

您怎么看?

1 个答案:

答案 0 :(得分:6)

您可以使用Select的重载来预测元素的索引以初始化匿名类型:

return cards
    .Select((c, i) => new { Card = c, Index = i})
    .Where(x => x.Card.Selected)
    .Select(x => x.Index)
    .ToArray();   
相关问题