[英]C# How to declare lambda or anonymous function type in method argument list?
[英]How to declare List of anonymous type
在此官方ASP.NET MVC Core教程中,他們定義了如下ViewModel,其中Movie是類。 然后在Index(...)方法中(在本教程結束時,他們從一個簡單的LINQ查詢中填充ViewModel,如下面的Controller中所示):
ViewModel :
public class MovieGenreViewModel
{
public List<Movie> movies;
public SelectList genres;
public string movieGenre { get; set; }
}
控制器 :
public async Task<IActionResult> Index(string movieGenre, string searchString)
{
// Use LINQ to get list of genres.
IQueryable<string> genreQuery = from m in _context.Movie
orderby m.Genre
select m.Genre;
var movies = from m in _context.Movie
select m;
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
if (!String.IsNullOrEmpty(movieGenre))
{
movies = movies.Where(x => x.Genre == movieGenre);
}
var movieGenreVM = new MovieGenreViewModel();
movieGenreVM.genres = new SelectList(await genreQuery.Distinct().ToListAsync());
movieGenreVM.movies = await movies.ToListAsync();
return View(movieGenreVM);
}
問題 :在上述ViewModel中,屬性影片的類型為List<movie>
,而Index(...)方法中使用的查詢是僅包含一個表(影片)的簡單查詢。 但是,如果查詢涉及具有兩個表的INNER JOIN並因此返回匿名類型的對象,如下所示,該怎么辦? 在那種情況下,我們如何在ViewModel中聲明匿名類型List<.?.>
,然后在ViewModel中填充List <。?。>類型的屬性? 在下面的示例中,我使用List<dynamic>
或List<object>
定義了一個ViewModel,並嘗試了myViewModel.list = leftOuterJoinQuery.ToListAsync()
但由於Cannot implicitly convert type 'List<<anonymous type: int CategoryId, string CategoryName, string ProdName>>>' to 'System.Collections.Generic.List<dynamic>
而收到錯誤Cannot implicitly convert type 'List<<anonymous type: int CategoryId, string CategoryName, string ProdName>>>' to 'System.Collections.Generic.List<dynamic>
:
LINQ INNER JOIN查詢 :
var innerJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID
select new { ProductName = prod.Name, Category = category.Name }; //produces flat sequence
更新 :
如下@StephenMuecke所建議,可以通過創建另一個包含我的查詢返回的屬性的視圖模型來解決該問題。 但是我在考慮是否有辦法避免創建額外的視圖模型。
有一種無需創建新VM即可完成此操作的方法,但是我不確定這是正確的方法。
首先,我將如下所示切換虛擬機
public class MovieGenreViewModel
{
public ICollection movies;
public SelectList genres;
public string movieGenre { get; set; }
}
定義一個輔助方法來組成匿名對象的列表
public static List<T> CreateList<T>(params T[] elements)
{
return new List<T>(elements);
}
最后,更改Index()方法內的行
從
movieGenreVM.movies = await movies.ToListAsync();
至
var output = await innerJoinQuery.ToListAsync();
movieGenreVM.movies = CreateList(output);
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.