যদিও আপনি অবশ্যই বিদ্যমান সিকোয়েন্স অপারেটরগুলির থেকে এই জাতীয় কোনও ডিভাইস তৈরি করতে পারেন, আমি এই ক্ষেত্রে কাস্টম সিকোয়েন্স অপারেটর হিসাবে এইটিকে লিখতে আগ্রহী। কিছুটা এইরকম:
// Returns "other" if the list is empty.
// Returns "other" if the list is non-empty and there are two different elements.
// Returns the element of the list if it is non-empty and all elements are the same.
public static int Unanimous(this IEnumerable<int> sequence, int other)
{
int? first = null;
foreach(var item in sequence)
{
if (first == null)
first = item;
else if (first.Value != item)
return other;
}
return first ?? other;
}
এটি বেশ পরিষ্কার, সংক্ষিপ্ত, সমস্ত কেসকে কভার করে এবং অযৌক্তিকভাবে ক্রমের অতিরিক্ত পুনরাবৃত্তি তৈরি করে না।
এটিকে কাজ করে IEnumerable<T>এমন একটি জেনেরিক পদ্ধতিতে তৈরি করা অনুশীলন হিসাবে ছেড়ে যায়। :-)