could someone help me with the linq statement,
this is what i have so far
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
开发者_JS百科 select IndexOf(board)
);
}
}
board is an item in category and when i pass a bordId ( which is not an index ) it must search for that BoardId in all boards in each category and then return the Index Of that board
how do i do it using Linq?
Thank you so much for all your help!!!
EDIT
This is a much simpler version of the same thing:
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();
}
Original Version
To get the index of the first matching Board in its own Category, first find the Category, then get the index of the 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);
}
To get the index of the first matching Board in a flattened collection amongst all of the Categories, then @Dan Tao has the best answer.
It looks to me like you want something like this:
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);
}
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).
Ok, without seeing the object class, I can't be sure, but it should be close to this:
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());
}
精彩评论