2017-05-03 99 views
0

我有一個枚舉集的LINQ查找集合中的所有項目從其他集合

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(m yEnums)。 Thks

+0

那你試試? –

回答

2

試試這個: myObjects.Where(m => m.MyEnums.Intersect(myEnums).Any());

-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(); 

     } 
    } 
} 
相關問題