Is this possible with IList

I have an open class Profile. A very simple model class currently with 2 properties; string Nameand string Fields. As the project develops, the class will expand, but this is not particularly important at the moment.

I have a Global static IListtype Profilecalled Profiles. I am new to data manipulation in these types IEnumerable, but I want to update one of the properties of one profile. I tried the following, but I get a reference to an object not throwing an exception. Below I set the property:

Profiles.Single(x => x.Name == listBoxProfiles.Text).Fields = textBoxFieldName.Text;

The debugger shows that the properties of the list text and text field have the correct values, so I think this is how I use a single that is incorrect.

If anyone could shed light, I would be grateful.

+3
source share
1 answer

A simple amendment to make the code more secure is all that is required:

var profile = Profiles.SingleOrDefault(x => x.Name == listBoxProfiles.Text);

if (profile != null)
{
    profile.Fields = textBoxFieldName.Text;
}
else
{
    Profiles.Add(new Profile(textBoxFieldName.Text));
}

This code will handle missing values, SingleOrDefaultexpect to return 0 or 1 elements. It throws an exception if more than 1 element is found.

If you know that your code should always have the element you are looking for, then your code will work, but I would advise against this style of programming in favor of being a bit more secure.

+1
source

All Articles