ICollection - Get single value

后端 未结 5 863
孤街浪徒
孤街浪徒 2021-02-03 17:45

What is the best way to get a value from a ICollection? We know the Collection is empty apart from that.

5条回答
  •  死守一世寂寞
    2021-02-03 17:53

    Without generics and because ICollection implements IEnumerable you can do like in example 1. With generics you simple need to do like example 2:

    List l = new List();
    l.Add("astring");
    
    ICollection col1 = (ICollection)l;
    ICollection col2 = (ICollection)l;
    
    //example 1
    IEnumerator e1 = col1.GetEnumerator();
    if (e1.MoveNext())
        Console.WriteLine(e1.Current);
    
    //example 2
    if (col2.Count != 0)
        Console.WriteLine(col2.Single());
    

提交回复
热议问题