code_junkie

C# ICollection get single value

Nov 12th, 2011
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. var foo = myICollection.OfType<YourType>().FirstOrDefault();
  2. // or use a query
  3. var bar = (from x in myICollection.OfType<YourType>() where x.SomeProperty = someValue select x)
  4. .FirstOrDefault();
  5.  
  6. foreach(object o in collection) {
  7. return o;
  8. }
  9.  
  10. IEnumerator en = collection.GetEnumerator();
  11. en.MoveNext();
  12. return en.Current;
  13.  
  14. IList iList = collection as IList;
  15. if (iList != null) {
  16. // Implements IList, so can use indexer
  17. return iList[0];
  18. }
  19. // Use the slower way
  20. foreach (object o in collection) {
  21. return o;
  22. }
  23.  
  24. List<string> l = new List<string>();
  25. l.Add("astring");
  26.  
  27. ICollection col1 = (ICollection)l;
  28. ICollection<string> col2 = (ICollection<string>)l;
  29.  
  30. //example 1
  31. IEnumerator e1 = col1.GetEnumerator();
  32. if (e1.MoveNext())
  33. Console.WriteLine(e1.Current);
  34.  
  35. //example 2
  36. if (col2.Count != 0)
  37. Console.WriteLine(col2.Single());
Add Comment
Please, Sign In to add comment