Jonathan Jonathan -4 years ago 64
C# Question

Get values from list that match BOTH attributes using c# LINQ

I have the following code and I need to get ALL IndividualRefs that match both Attributes - it needs to get all using an AND not an OR. For example the code below should only get me Individual ref 22 as he matches "ST" AND "BJOG"

Do you know a LINQ statement that would do this?

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


Of course the AttributeList can grow in size.
Thanks

Answer Source

Use list or array to hold all attributes which you need to check. Search can be done with LINQ - create the individuals lookup which returns all individual attribute codes by ref, then check whether group contains all attributes:

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download