![](/img/trans.png)
[英]How to find one value from an IQueryable in C# ASP.NET MVC 4 using Linq?
[英]Using Linq to get value from a model asp.net mvc
我的模型不是很簡單明了,我想從中獲取某些數據,但是我對Linq或要使用的命令不太熟悉。 這是模型代碼:
public class RootObject
{
public string _id { get; set; }
public string court { get; set; }
public string type { get; set; }
public string caption { get; set; }
public Case cases { get; set; }
public Dates dates { get; set; }
public Judge judge { get; set; }
public Balance balance { get; set; }
public Sentence sentence { get; set; }
public List<Charge> charges { get; set; }
public List<Participant> participants { get; set; }
}
public class Participant
{
public string _id { get; set; }
public string type { get; set; }
public int partyNumber { get; set; }
public Name2 name { get; set; }
public Address address { get; set; }
public Phone phone { get; set; }
public Birth birth { get; set; }
public List<Cost> costs { get; set; }
public List<Receipt> receipts { get; set; }
}
public class Name2
{
public string prefix { get; set; }
public string first { get; set; }
public string middle { get; set; }
public string last { get; set; }
public string suffix { get; set; }
public string company { get; set; }
public string full { get; set; }
}
我基本上是想通過根對象和參與者列表來獲取Name2類中的名字和姓氏或全名。 我正在使用asp.net 5,mvc 6和linq來調用對象,但是由於我的linq不正確,所以似乎無法獲取該值。 該模型按照IEnumerable列表的形式傳遞給視圖類,這是用於嘗試獲取名稱的代碼:
@foreach (var item in Model)
{
@item.participants.Select(i => i.name.full);
}
任何幫助,將不勝感激。
感謝您的時間
對不起,我很晚才回復,但這對我有用:
@foreach (var item in Model.participants)
{
<p>@item.name.first</p>
}
嘗試這個:
@foreach (var item in Model)
{
@foreach (var item2 in item.participants)
{
<p>@item2.name.full</p>
<p>@item2.name.first</p>
<p>@item2.name.last</p>
}
}
其他選項-每個條目一個名稱:
@foreach (var item in Model)
{
<p>@item.participants.FirstOrDefault()?.name.full</p>
<p>@item.participants.FirstOrDefault()?.name.first</p>
<p>@item.participants.FirstOrDefault()?.name.last</p>
}
尚不清楚您要如何顯示這些名稱,但讓我們假設您希望它們以“名稱1,名稱2,名稱3”的形式顯示。 然后變成:
@String.Join(", ", item.participants.Select(p => p.name.first + " " + p.name.last))
但是,如果每個項目只顯示一個名稱,例如第一個,則可以使用First()
:
@item.participants.First(p => p.name.full)
最后,如果由於某些原因參與者列表可能為空,請使用FirstOrDefault
。 這將為空列表輸出null,因此請確保正確處理!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.