2017-06-14 89 views
1

我有以下代碼,我需要獲得所有與兩個屬性匹配的IndividualRefs - 它需要使用AND而不是OR來獲得所有。例如下面的代碼應該只給我個人參考22,因爲他匹配「ST」和「BJOG」從列表中獲得匹配兩個屬性的值使用c#LINQ

你知道一個LINQ語句嗎?

string AttributeList = "ST,BJOG,"; 
     List<StratogIndividuals> inds = new List<StratogIndividuals>(); 
     StratogIndividuals s = new StratogIndividuals(); 
     string[] attributes = AttributeList.Split(',').Where(x => x != "").ToArray(); 

     s.AttributeCode = "ST"; 
     s.IndividualRef = "22"; 
     inds.Add(s); 

     s = new StratogIndividuals(); 
     s.AttributeCode = "BJOG"; 
     s.IndividualRef = "22"; 
     inds.Add(s); 

     s = new StratogIndividuals(); 
     s.AttributeCode = "BJOG"; 
     s.IndividualRef = "20"; 
     inds.Add(s); 

     s = new StratogIndividuals(); 
     s.AttributeCode = "XXF"; 
     s.IndividualRef = "21"; 
     inds.Add(s); 

當然AttributeList的大小可以增加。 謝謝

+0

'inds.GroupBy(IND => ind.IndividualRef)。凡(G =>新的HashSet (g.Select(IND => ind.AttributeCode))。SetEquals(新[] { 「BJOG」 ,「ST」}))。Select(g => g.Key)' – spender

+0

使用GroupBy inds.GroupBy(x => new {attr = x.AttributeCode,ref = x.INdividual}) – jdweng

回答

1

使用列表或數組來保存所有需要檢查的屬性。搜索可以使用LINQ來完成 - 創建個人查找其由參返回所有單個屬性代碼,然後檢查組是否包含所有的屬性:

var attributes = new []{ "ST", "BJOG" }; 

var refs = inds.ToLookup(i => i.Ref, i => i.AttributeCode) 
       .Where(g => !attributes.Except(g).Any()) 
       .Select(g => g.Key); 
0

請試試這個。使用GroupBy IndividualRef然後使用SetEqual以使其與屬性匹配。

List<StratogIndividuals> inds = new List<StratogIndividuals>(){ 
      new StratogIndividuals(){ AttributeCode = "ST", IndividualRef = "22"}, 
      new StratogIndividuals(){ AttributeCode = "BJOG", IndividualRef = "22"}, 
      new StratogIndividuals(){ AttributeCode = "BJOG", IndividualRef = "20"}, 
      new StratogIndividuals(){ AttributeCode = "XXF", IndividualRef = "21"}, 
     }; 

     string AttributeList = "ST,BJOG,"; 
     string[] attributes = AttributeList.Split(',').Where(x => x != "").ToArray(); 

     var results = inds.GroupBy(ind => ind.IndividualRef) 
      .Where(g => new HashSet<string>(g.Select(i => i.AttributeCode)).SetEquals(attributes)) 
      .Select(x => x.Key).ToList(); 
相關問題