2016-05-30 43 views
0

我有一个不是非常简单直接的模型,我想从中获取某些数据,但我对Linq或者使用的命令不太熟悉。下面是型号代码:使用Linq从模型asp.net获取价值mvc

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; } 
} 

我基本上是试图去通过根对象和参与者列表名称2类的名字和姓氏或全名。我正在使用asp.net 5和mvc 6和linq来调用这些对象,但由于我的linq不正确,似乎无法获取值。该模型中的IEnumerable列表视图类过去了,这里是用来尝试并获得名称代码:

@foreach (var item in Model) 
{ 
    @item.participants.Select(i => i.name.full); 
} 

任何帮助,将不胜感激。

谢谢您的时间

+0

你想将所有名称显示为单个字符串的名称? – Andrei

+0

道歉不清楚。我想为每个条目显示一个名称。 –

回答

2

对不起已故的答复,但是这个工作对我来说:

@foreach (var item in Model.participants) 
{ 
    <p>@item.name.first</p> 
} 
0

尚不完全清楚要如何显示这些名字,但是让我们假设你希望他们在“名称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,所以请确保正确处理它!

1

试试这个:

@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> 
}