Using List.Find or LINQ in Listing Lists in .NET 3.5

Why does List.Find (and LINQ queries in a list) always return the first element of an enumeration when the list does not contain the element I'm looking for?

Scenario:

My listing:

public enum TestEnum
{
    EnumOne,
    EnumTwo,
    EnumThree
}

My test:

var TestEnum1 = TestEnum.EnumOne;
var TestEnum2 = TestEnum.EnumTwo;
var TestEnum3 = TestEnum.EnumThree;

List<TestEnum> testEnumList = new List<TestEnum>();//{ TestEnum1, TestEnum2 };
var selectedWithLinq = (from c in testEnumList where c.Equals(TestEnum3) select c).FirstOrDefault();
var selectedWithListFind = testEnumList.Find(myEnum => TestEnum3.Equals(myEnum)));

Both selectedWithLinq and selectedWithListFind in this case return TestEnum.EnumOne. If I add TestEnum3 to the list, it will return correctly.

+3
source share
5 answers

TestEnum - , , null ( , ), default(TestEnum), EnumOne . , ?

+10

, , . :

  • :

    var selectedWithLinq = testEnumList.Where(x => x == TestEnum3)
                                       .Select(x => (TestEnum?) x)
                                       .FirstOrDefault();
    if (selectedWithLinq != null)
    {
       var realValue = selectedWithLinq.Value;
        // etc
    }
    
  • TryXXX:

    public static bool TryFirst<T>(this IEnumerable<T> source,
                                   out T found)
    {
        using (IEnumerator<T> iterator = source.GetEnumerator())
        {
            if (iterator.MoveNext())
            {
                found = iterator.Current;
                return true;
            }
            else
            {
                found = default(T);
                return false;
            }
        }
    }
    
+3

, , , .

+2

The default value TestEnumwill be the first item, so when you do .FirstOrDefault(), it TestEnum.EnumOnewill be returned as the default when you cannot find the "first" that matches your criteria.

0
source

this will help you get a list of values ​​in Enum for a general list. No need to add a static extension.

var _allEnumVals = ((MyEnum[])Enum.GetValues(typeof(MyEnum))).ToList();
0
source

Source: https://habr.com/ru/post/1722572/


All Articles