Có cách nào "LINQ" để có lựa chọn dữ liệu có điều kiện, tức là chọn từ nguồn khác nếu nguồn đầu tiên trống? Một ví dụ là nếu bạn có cấu trúc cây của các mục và bạn muốn lấy một số nội dung từ gốc hoặc nếu nó trống, từ đó là con.Lựa chọn có điều kiện trong LINQ (chọn thay thế nếu trống)
Tôi có ví dụ sau:, phương pháp khuyến nông
IEnumerable<Item> items = ...;
// Item has a Assets property that returns IEnumerable<Asset>
// Item has a SubItems property that returns IEnumerable<Item>
// i.e. other items with assets in them
// getting assets from a "main" item
var assets = item.Assets.Where(a => HasRelevantAsset(a));
// if there were no relevant assets in the "main" item
if (!assets.Any()) {
// then reselect from "subitems" assets instead
assets = item.SubItems.SelectMany(item =>
item.Assets.Where(a => HasRelevantAsset(a)));
}
// HasRelevantAsset(Asset) is a static method that returns
// true if it is the asset that is needed
Điều này có vẻ giống như sử dụng khá tốt cho ?? toán tử - 'var asset = something ?? something_else'. Nó sẽ không hoạt động, nhưng nó sẽ là tốt đẹp nếu nó đã làm. – zmbq