Reputation: 10799
Can somebody help me on the Lambda expression.
My ModelVM looks like :
namespace MReports.Models
{
public class FullDetailVM
{
public FullDetailVM()
{
DetailSet = new List<FullDetailSet>();
}
........
public List<FullDetailSet> DetailSet { get; set; }
}
public class FullDetailSet
{
public FullDetailSet(){ }
public string Mnum { get; set; }
public string Label { get; set; }
public string LabelValue { get; set; }
}
}
Data in the above model will be :
DetailSet[0] = {1,"MCity","LosAngeles"}
DetailSet[0] = {1,"MState","California"}
DetailSet[0] = {1,"MZip","90045"}
DetailSet[0] = {1,"MStreet","Cardiff"}
DetailSet[0] = {1,"MHouse No","1234"}
DetailSet[0] = {1,"MApt","1"}
View(Razor) :
@model MReports.Models.FullDetailVM
@if(Model != null)
{
<div class="row contentHeaderInfo">
<ul class="list-inline">
<li> City :
</li>
<li>
//Display LabelValue corresponding to Mcity
Model.DetailSet.select(LabelValue).Where(Label== "Mcity");
</li>
<li> State:
</li>
<li>
//Display LabelValue corresponding to MState
Model.DetailSet.select(LabelValue).Where(Label== "MState");
</li>
</ul>
</div>
}
Upvotes: 0
Views: 131
Reputation: 400
Lambda expressions can be used to create delegate types. I've found the easiest way to explain this to someone is to show them a list of items, such as your List<FullDetailSet> DetailSet
, and ask them what items from that list do you want based on a specific condition?
If you wanted all the items with label "Dog" you would do something like this:
Model.DetailSet.Where(d => d.Label == "Dog").Select(d => d.Value);
This will go over the items in DetailSet
and check if each item has a Label
of "Dog". For lack of a better understanding on the correct terminology, you are iterating over that list and grabbing what you need based on your conditions. This is why I used d
as the placeholder, to me it looks as though d
is a singluar representation of DetailSet
.
If you needed only one record from that DetailSet
you would use Single
over Where
.
Model.DetailSet.Single(d => d.Label == "Dog").Select(d => d.Value);
If you didn't need just the Value
of those records that met your conditions you can grab the entire list like this:
Model.DetailSet.Where(d => d.Label == "Dog").ToList();
Upvotes: 1
Reputation: 7211
You need to select one record using Single
, then just get the property.
Model.DetailSet.Single(m => m.Label == "MState").LabelValue
Upvotes: 1
Reputation: 10901
Model.DetailSet.Where(x=>x.Label == "Mcity").Select(x=>x.LabelValue)
or if you have just one recors Label == Mcity
Model.DetailSet.SingleOrDefault(x=>x.Label == "Mcity").LabelValue
Upvotes: 3