代码之家  ›  专栏  ›  技术社区  ›  Learner

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

  •  1
  • Learner  · 技术社区  · 12 年前

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

    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 回复  |  直到 12 年前
        1
  •  6
  •   Tim Schmelter    12 年前

    您可以使用 Select 其投影元素的索引以初始化匿名类型:

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