简体   繁体   English

比较两个列表:一个包含对象,另一个包含字符串

[英]Compare two lists : One contain object, one other contain string

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...目前,我正在使用双 foreach,但我知道 LinQ 可以实现,但我不知道如何...

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.感谢您的帮助。

Using a Where and Contains (not as efficient).使用 Where 和 Contains (效率不高)。

List<Light> lightsIWant = (await this.bridgeManager.GetLights())
    .Where(l => lightsWanted.Contains(l.Name))
    .ToList();

Using a Join (more efficient)使用 Join(更高效)

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.您也可以使用扩展方法进行连接,我只是更喜欢使用查询语法来处理这样的简单内容。

您可以为此目的使用 Join

var selectedList = lights.Join(lightsWanted,x=>x.Name,y=>y,(x,y)=>x);

This should do it:这应该这样做:

List<Light> lightsIwant = (from l in lights
                           join lw in lightsWanted on l.Name equals lw
                           select l).ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何比较两个泛型列表一个包含int和另一个包含类对象 - How to Compare two Generic List one contain int and another contain class object 将两个列表与linq和lambda进行比较,其中一个是字符串,另一个是长整数 - Compare two lists with linq and lambda where one is string and other long 如何比较两个包含包含字典的对象的列表? - How to compare two lists that contain objects that contain Dictionaries? 比较包含大量对象的两个列表 - Compare two lists that contain a lot of objects 比较两个包含很多对象的列表(第二部分) - Compare two lists that contain a lot of objects (2th part) 一个对象池包含不同的派生类 - One object pool to contain different derived classes 我有两个datagridview,一个在员工电话上,我想让另一个包含打过电话的员工人数 - I have two datagridview, one on the staff calls, I want to make the other contain the number of staff did the call 使用 LINQ 比较两个列表,并生成第三个列表,其中一个或另一个的结果 - Use LINQ to compare two lists, and produce a third one with results from one OR the other 比较两个列表以确定两个列表是否使用lambda谓词包含相同的项目 - Compare two lists to determine if both lists contain same items using lambda predicates Linq比较两个对象列表,其中一个对象有多个列表 - Linq to compare two lists of objects where one object has several lists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM