Foreach Int in Yield Return: (I Data) I
Foreach Int in Yield Return: (I Data) I
{
int[] data = { 1, 2, 3 };
// The generic enumerator is compatible with both IEnumerable and
// IEnumerable<T>. We implement the nongeneric GetEnumerator method
// explicitly to avoid a naming conflict.
public IEnumerator<int> GetEnumerator()
{ return new Enumerator(this); }
IEnumerator IEnumerable.GetEnumerator()
{ return new Enumerator(this); }
class Enumerator : IEnumerator<int>
{
int currentIndex = -1;
MyIntList collection;
public Enumerator(MyIntList collection)
{
this.collection = collection;
}
public int Current { get { return collection.data[currentIndex]; } }
object IEnumerator.Current { get { return Current; } }
public bool MoveNext()
{
return ++currentIndex < collection.data.Length;
}
public void Reset() { currentIndex = -1; }
// Given we don't need a Dispose method, it's good practice to
// implement it explicitly, so it's hidden from the public interface.
void IDisposable.Dispose() { }
}
}
*********************************
public class MyGenCollection : IEnumerable<int>
{
int[] data = { 1, 2, 3 };
public IEnumerator<int> GetEnumerator()
{
foreach (int i in data)
yield return i;
}
IEnumerator IEnumerable.GetEnumerator() // Explicit implementation
{
// keeps it hidden.
return GetEnumerator();
}
}
************************************
public class Test
{
public static IEnumerable<int> GetSomeIntegers()
{
yield return 1;
yield return 2;
yield return 3;
}
}
-foreach (int i in Test.GetSomeIntegers())
Console.WriteLine(i);
1
2
3
class Entliczek2 : IEnumerable<char>
Sorting
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
Temperature otherTemperature = obj as Temperature;
if (otherTemperature != null)
if(this.tempF>otherTemperature.tempF)
return 1;
else if( this.tempF<otherTemperature.tempF)
return-1;
else
return 0;
else
throw new ArgumentException("Object is not a Temperature");
IComparer
class Kaczka
{
public int Wiek { get; set; }
public int Waga { get; set; }
}
class KaczkaComapreByWaga : IComparer<Kaczka>
{
int IComparer<Kaczka>.Compare(Kaczka x, Kaczka y)
{
if (x.Waga < y.Waga)
return -1;
else if (x.Waga < y.Waga)
return 1;
else
return 0;
}
class KaczkaCompareByWiek : IComparer<Kaczka>
{
public int Compare(Kaczka x, Kaczka y)
{
return x.Wiek.CompareTo(y.Wiek);
}
}
List<Kaczka> kaczaList = new List<Kaczka>
{ new Kaczka { Wiek = 12, Waga = 13 },
new Kaczka { Wiek = 15, Waga = 11 },
new Kaczka { Wiek = 1, Waga = 14 },
new Kaczka { Wiek = 18, Waga = 19 },
new Kaczka { Wiek = 11, Waga = 4 }
};
kaczaList.Sort(new KaczkaCompareByWiek());
foreach (var k in kaczaList)
Console.WriteLine("Wiek: {0}, Waga: {1},", k.Wiek, k.Waga);
class Kaczka
{
public int Wiek { get; set; }
public int Waga { get; set; }
}
kaczaList.Sort(Kaczka.ByWiek);
Array.Sort(tablicaDoPosortowania, new IComparerClass());