1

有人可以帮我处理 linq 语句吗?

这就是我到目前为止所拥有的

public class Categories : ObservableCollection<Category>
{ 
    public Categories() { } 

    public int getBoardIndex(int BoardId)
    {
        return (from category in this
                from board in category.CategoryBoards
                where board.BoardId == BoardId
                select IndexOf(board)
                    );
    }
}

board 是类别中的一个项目,当我传递一个bordId(不是索引)时,它必须在每个类别的所有板中搜索该 BoardId,然后返回该板的索引

我如何使用 Linq 做到这一点?

非常感谢您的帮助!!!

4

4 回答 4

1

编辑

这是同一件事的一个更简单的版本:

public int getBoardIndex(int BoardId)
{
    return (from category in this
            from board in category.CategoryBoards
            where board.BoardId == BoardId
            select category.CategoryBoards.ToList().IndexOf(board)).FirstOrDefault();
}

原版

要获取自己Category中第一个匹配的Board的索引,首先找到Category,然后获取Board的索引:

public int getBoardIndex(int BoardId)
{

    var categoryBoard = (from category in this
                         from board in category.CategoryBoards
                         where board.BoardId == BoardId
                         select new {category, board}).FirstOrDefault();
    return categoryBoard.category.CategoryBoards.IndexOf(categoryBoard.board);
}

要在所有类别中的扁平集合中获得第一个匹配板的索引,那么@Dan Tao 有最好的答案。

于 2011-05-27T20:45:52.383 回答
1

在我看来你想要这样的东西:

public int getBoardIndex(int BoardId)
{
    var potentialBoards = from category in this
                          from board in category.CategoryBoards
                          select board;

    return potentialBoards.ToList().FindIndex(b => b.BoardId == BoardId);
}
于 2011-05-27T20:28:27.360 回答
0

So far, you have an IEnumerable, containing the indices of any board IDs that matched.

If you know that there is exactly one board that matches, you can call .Single() and return that single index. If there might or might not be one board that matches, then you can call .ToList() and assign the result to a variable. Then check whether the list has any items and either return the first item or -1 (or throw an exception, or whatever).

于 2011-05-27T20:19:48.543 回答
0

好的,没有看到对象类,我不能确定,但​​它应该接近这个:

public static int getBoardIndex(this ObservableCollection<Category> coll, int BoardId)
{
    return coll.IndexOf((
                from category in coll
                from board in category.CategoryBoards
                where board.BoardId == BoardId
                select category).FirstOrDefault());
}
于 2011-05-27T20:24:49.990 回答