在下面的方法中,我想返回一个包含所选卡片索引的数组:
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));
你觉得怎么样?
你可以使用Select
的重载来初始化一个匿名类型:
return cards
.Select((c, i) => new { Card = c, Index = i})
.Where(x => x.Card.Selected)
.Select(x => x.Index)
.ToArray();