我有以下代码,我需要获得与两个属性匹配的所有IndividualRef - 它需要使用AND而不是OR。例如,下面的代码应该只给我个人参考22,因为他匹配" ST"和" BJOG"
你知道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 :(得分:1)
使用列表或数组来保存您需要检查的所有属性。可以使用LINQ进行搜索 - 创建个人查找,通过ref返回所有单独的属性代码,然后检查组是否包含所有属性:
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);
答案 1 :(得分: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();