Linq从其他收藏中查找收藏中的所有项目

时间:2017-05-03 15:22:19

标签: c# linq collections find contain

我有一个枚举集

    List<MyEnum> myEnums = new List<MyEnum>{MyEnum.Item1, MyEnum.Item2}

我有一个对象集合

List<MyObject> myObjects = MyObjects.GetMyObjects ();

MyObject有一个MyEnum

列表的属性
myObjects[0].MyEnums  /* contain {MyEnum.Item1, MyEnum.Item5, MyEnum.Item6} */

我想找到所有myObjects属性myObject.MyEnums包含MyEnum.Item1或MyEnum.Item2(myEnums)。 THKS

2 个答案:

答案 0 :(得分:2)

试试这个: myObjects.Where(m => m.MyEnums.Intersect(myEnums).Any());

答案 1 :(得分:-1)

试试这个:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class Program
    {
        public enum MyEnum { Item1, Item2, Item3 }
        public class MyObject
        {
            public List<MyEnum> myEnums;
            public MyObject(List<MyEnum> myEnums)
            {
                this.myEnums = myEnums;
            }
        }


        static void Main(string[] args)
        {
            List<MyEnum> myEnums1 = new List<MyEnum> { MyEnum.Item1, MyEnum.Item2 };
            List<MyEnum> myEnums2 = new List<MyEnum> { MyEnum.Item1 };
            List<MyEnum> myEnums3 = new List<MyEnum> { MyEnum.Item3 };

            List<MyObject> myObjects = new List<MyObject>();

            myObjects.Add(new MyObject(myEnums1));
            myObjects.Add(new MyObject(myEnums2));
            myObjects.Add(new MyObject(myEnums3));



            List<MyEnum> myEnumsFind = new List<MyEnum> { MyEnum.Item1, MyEnum.Item2 };

            var result = myObjects.Where(x => myEnumsFind.Any(y => x.myEnums.Contains(y))).ToList();

        }
    }
}