简体   繁体   中英

Convert and check if struct IList contains nullable int. c#

I have a struct named CheckedNumber . This type is used in a property:

`public IList<CheckedNumber> CheckedNumbers { get { return this._checkedNumbers; } }` 

...to keep a list of numbers.

I have another property:

`public int? TheNumber { get { return this._theNumber; } }`

...and want to check if its value exists in the CheckedNumbers list.

this:

if (this.CheckedNumbers.Contains(this.TheNumber)) { //... }

gives error:

Argument 1: cannot convert from 'int?' to 'ProjectName.Models.CheckedNumber'

How could I convert int? to my struct type?

Okay, now the question is slightly clearer - but fundamentally, you're asking whether a list of CheckedNumber values contains a particular int? value. That makes no sense, as an int? isn't a CheckedNumber - it's like asking whether a List<Fruit> contains a car.

If part or your CheckedNumber struct is an int? , you might want:

if (CheckedNumbers.Any(x => x.SomeProperty == TheNumber))

Alternatively, you might want:

if (CheckedNumbers.Contains(new CheckedNumber(TheNumber)))

Otherwise, you'll have to clarify the question further.

Let CheckedNumber implement IEquatable<CheckedNumber> . The Contains method of your list can then use this method to find list items.

public struct CheckedNumber : IEquatable<CheckedNumber>
{
    public CheckedNumber(int? number)
    {
        _value = number;
    }

    private int? _value;
    public int? Value { get { return _value; } }

    public bool Equals(CheckedNumber other)
    {
        return _value == other._value;
    }
}

Now you can do your check by converting the int? to a CheckedNumber

if (this.CheckedNumbers.Contains(new CheckedNumber(this.TheNumber))) {
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM