简体   繁体   中英

Selecting single attribute of elements from a list object based on another Hashset's element

I have a list object type of some class,

class person
{
    public string id { get; set; }
    public string regid { get; set; }
    public string name { get; set; }
}

List<person> pr = new List<person>();
pr.Add(new person { id = "2",regid="2222", name = "rezoan" });
pr.Add(new person { id = "5",regid="5555", name = "marman" });
pr.Add(new person { id = "3",regid="3333", name = "prithibi" });

and a HashSet of type string,

HashSet<string> inconsistantIDs = new HashSet<string>();
inconsistantIDs.Add("5");

Now i want to get only all the * regid *s from pr list that contains the id's in the inconsistantIDs HashSet and store them into an another HashSet of type string.

i have tried but can only get all the person that has the id's in inconsistantIDs list(This is only an example).

 HashSet<person> persons = new HashSet<person>(
            pr.Select(p=>p).Where(p=>
                    inconsistantIDs.Contains(p.id)
                ));

Could anyone help me out there?

var regIDs = from p in pr join id in inconsistantIDs on p.id equals id
             select p.regid;
HashSet<string> matchingRegIDs = new HashSet<string>(regIDs); // contains: "5555"

I am not sure what is your desired output, but I will try anyway:

HashSet<string> persons = new HashSet<string>(
            pr.Select(p=>p.regid)
              .Where(p=> inconsistantIDs.Any(i=>p.Contains(i))));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM