سؤال

class Foo
{
    int PrimaryItem;
    bool HasOtherItems;
    IEnumerable<int> OtherItems;
}

List<Foo> fooList;

كيف يمكنني الحصول على قائمة بجميع معرفات العناصر المشار إليها في الداخل fooList?

var items = fooList
             .Select(
              /*
                f => f.PrimaryItem;
                if (f.HasOtherItems)
                    AddRange(f => f.OtherItems)
              */  
              ).Distinct();
هل كانت مفيدة؟

المحلول

يستخدم SelectMany واطلب من ذلك إرجاع قائمة متسلسلة من PrimaryItem و OtherItems (إذا كانت موجودة):

var result = fooList
    .SelectMany(f => (new[] { f.PrimaryItem })
        .Concat(f.HasOtherItems ? f.OtherItems : new int[] { }))
    .Distinct();

نصائح أخرى

كاختلاف طفيف:

var items = fooList.Select(i => i.PrimaryItem).Union(
      fooList.Where(foo => foo.HasOtherItems).SelectMany(foo => foo.OtherItems));

هذا يأخذ مجموعة من PrimaryItem, ، و أين HasOtherItems تم تعيينه) يسلط المجموعة المشتركة من OtherItems. ال Union يضمن متميز.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top