I have a list of codes as follows
public Code{
int id;
string Description;
}
List<Code> AllCodes;
I have a list of selected codes from a different source.
var relatedCodes = //gets the list of int 'id's from a different source.
Using linq
, I need to join AllCodes
and relatedCodes
so that the resultant list contains all the Code
elements of the given id
s. It is known that all the int
values in relatedCodes
are valid id
s in AllCodes
. [ relatedCodes
is an int
array]
result = //how to write the linq expression?
I was trying something like this but it throws error
result = AllCodes.All(x => x.Code==relatedCodes);
List<Code> result = AllCodes.Where(x => relatedCodes.Contains(x.id)).ToList();
First of all there is nothing to do with Join
. Question is briefly How can I get the Codes of which relatedCodes contains the id?
. You can use Where
to filter your list.
var result = AllCodes.Where( c=> relatedCodes.Contains(c.id));
EDIT: Since relatedCodes
is of type int[]
(I used an array of type Code
) the solution looks slightly different, but not by too much:
var relatedCodes = new int[2] { 2, 4 };
var joinedCodes = from ac in AllCodes
join rc in relatedCodes on ac.Id equals rc
select ac;
ORIGINAL answer
One possibility is to use join:
void Main()
{
var AllCodes = new List<Code>()
{
new Code() {Id = 1, Description="Foo1"},
new Code() {Id = 2, Description="Bar2"},
new Code() {Id = 3, Description="Foo3"},
new Code() {Id = 4, Description="Bar4"}
};
var relatedCodes = new Code[2]
{
new Code() {Id = 2, Description="Bar2"},
new Code() {Id = 4, Description="Bar4"}
};
var joinedCodes = from ac in AllCodes
join rc in relatedCodes on ac.Id equals rc.Id
select ac;
joinedCodes.Dump();
}
// Define other methods and classes here
public class Code{
public int Id { get; set; }
public string Description { get; set; }
}
Ouput:
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.