Reputation: 959
I'm trying to compare two list to add (in an other list) my lights that I want. I want to get light object by string name
For the moment, I'm using a double foreach, but I know it's possible with LinQ but I don't know how...
private readonly string[] lightsWanted = { "MyLight1", "MyLight2" };
---
var lights = await this.bridgeManager.GetLights();
foreach (Light light in lights)
{
foreach (string lightWanted in this.lightsWanted)
{
if (light.Name == lightWanted)
{
this.selectedLights.Add(light);
}
}
}
Thank you for your help.
Upvotes: 1
Views: 51
Reputation: 1335
This should do it:
List<Light> lightsIwant = (from l in lights
join lw in lightsWanted on l.Name equals lw
select l).ToList();
Upvotes: 1
Reputation: 18155
You could use Join for the purpose
var selectedList = lights.Join(lightsWanted,x=>x.Name,y=>y,(x,y)=>x);
Upvotes: 1
Reputation: 17545
Using a Where and Contains (not as efficient).
List<Light> lightsIWant = (await this.bridgeManager.GetLights())
.Where(l => lightsWanted.Contains(l.Name))
.ToList();
Using a Join (more efficient)
var allLights = await this.bridgeManager.GetLights();
IEnumerable<Light> lightsIWant = from allLight in allLights
join desiredLightName in lightsWanted
on allLight.Name equals desiredLightName
select allLight;
You can do a Join using Extension Methods as well, I just prefer using the query syntax for simple stuff like this.
Upvotes: 1