LINQ select from TList?
I have a list of RowData
items (a custom class).
A RowData
item contains a list of CellData
items (another custom class).
Currently, the only way I can access each individual CellData
item is through the RowData
's this[int index]
, which means I'd h开发者_如何转开发ave to create a loop for each search.
What I want is to create a method that will return all of the CellData
items for a given index
value:
private List<RowData> rowList;
public IEnumerable<CellData> Cells(int index) {
foreach (var row in rowList) {
if (row.ID == index) {
return row.AsEnumerable<CellData>();
}
}
return null;
}
I don't like returning NULL
, and I'd like to know how to accomplish this task using some LINQ techniques (either Query or Method syntax).
To be able to use LINQ syntax for getting cells collection from row, your RowData
need to be enumerable, i.e. implement IEnumerable
interface.
By .AsEnumerable<CellData>()
in your example, I assume your RowData
already implements it and enumerating RowData
returns collection of CellData
objects.
If not, you need to implement IEnumerable
in RowData
on your own. If your this[int index]
accessor reads the data from a collection, you can just return that collection's GetEnumerator
.
And then, you'll be able to fetch CellData
collection from RowData
collection using LINQ queries, i.e. like this:
var cells = rowList.Where(x => x.ID == index).SelectMany(x => x);
Assuming only one row is returned given an index:
public IEnumerable<CellData> Cells(int index)
{
var foundRow = rowList.FirstOrDefault(row => row.ID == index);
//if no row was found, foundRow will be null
if(foundRow != null)
return foundRow.AsEnumerable<CellData>();
else
return new CellData[]; //return empty cells IEnumerable. Could also be new List<CellData>()
}
}
This code assumes foundRow.AsEnumerable<CellData>()
returns a IEnumerable<CellData>
.
You have to check for nullity, because row at a given index might nor be found.
This will achieve the same result.
var resultsList = from x in rowList
where x.ID == index
select x;
return resultsList;
public IEnumerable<CellData> Cells(int index){
var cells = (from r on rowList
where r.ID == index
select r.Cells).FirstOrDefault();
return cells;
}
What about:
List<CellData> cells = rowList.Where(x => x.Index == index).SelectMany(x => x.Cells).ToList();
精彩评论