Reputation: 59
I have a problem! I have found allots of people with the same problem but none of the answers helpt me.. Im trying to get an specific item from List<> but my result of "test" returns null, why?
public MainWindow()
{
InitializeComponent();
var modelList = new Model2();
modelList.MyPropertyList.Add(new Model1 { Name = "Hej1", MyProperty1 = true });
modelList.MyPropertyList.Add(new Model1 { Name = "Hej2", MyProperty1 = false });
var test = modelList.MyPropertyList.Find(x => x.Name == "Hej1").MyProperty1;
}
Upvotes: 1
Views: 130
Reputation: 20754
According to the OP Comments
how do you know it is null? – dotctor 1 hour ago
When i debug the value is null.. – Dennis Eriksson 1 hour ago
are you sure you check the value after executing the line? try adding `MessageBox.Show(test.ToString());) and see what is the result – dotctor 1 hour ago
I feel a shame of my question.. It was working the whole time! It was my fault that i read the value before it was declared to "test"! But thanks!! – Dennis Eriksson 1 hour ago
I think the problem is in the way you debugged your program. You have put a breakpoint on line var test = modelList.MyPropertyList.Find(x => x.Name == "Hej1").MyProperty1;
and the execution stops right before this line but you think that this line is already executed and Visual Studio shows the value of test
as null
in Autos window and this makes you think that the test
is really null. If you continue execution by pressing F10
or add a line like MessageBox.Show(test.ToString());
just to make the previous line executed or somehow show the value of test
you will find that it is not null
.
Upvotes: 3
Reputation: 1213
Instead of Find() try using the following:
var test = modelList.MyPropertyList.SingleOrDefault(model => model.Name == "Hej1");
if(test != null)
{
//-- do something here
}
Upvotes: -1
Reputation: 148524
Not much as an answer - but your code - should work fine.
void Main()
{
var modelList = new Model2();
modelList.MyPropertyList.Add(new Model1 { Name = "Hej1", MyProperty1 = true });
modelList.MyPropertyList.Add(new Model1 { Name = "Hej2", MyProperty1 = false });
var test = modelList.MyPropertyList.Find(x => x.Name == "Hej1").MyProperty1;
Console.WriteLine (test);
}
public class Model1
{
public string Name { get; set; }
public bool? MyProperty1 { get; set; }
}
public class Model2
{
public List<Model1> MyPropertyList { get; set; }
public Model2()
{MyPropertyList = new List<Model1>();
}
}
Result : True
.
Upvotes: 2