首页 > 解决方案 > 将列表与另一个列表进行比较并获取匹配项

问题描述

不确定我是否忽略了某些东西,但又是早上 8 点,我还没有喝咖啡。

我正在尝试获取一个列表以与另一个列表进行比较

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var products = new List<product>() {
                new product(){ Id = 1, Name="foogear", Price = 20 },
                new product(){ Id = 2, Name="foobeam" , Price = 23},
                new product(){ Id = 3, Name="foowrench" , Price = 25},
                new product(){ Id = 4, Name="foonut", Price = 27 },
                new product(){ Id = 5, Name="foobar", Price = 29 }
        };
        var products2 = new List<product>() {
                new product(){ Id = 1, Name="foogear", Price = 20 },
                new product(){ Id = 5, Name="foobar", Price = 29 }
        };
        // string[] array = { "foobar" };

        // List<string> listA = new List<string>();
        // listA.Add("foobar");     

        for (int i = 0; i < products2.Count; i++)
        {
            //get all products whose name is Bill
            var prodNames = from s in products
                            where s.Name == products2(i,1)
                            select s;    
            foreach (var product in prodNames)
            {
                var test = product.Price + 641;
                Console.WriteLine(product.Id + ", " + product.Name + " "+ test);
            }
        }
    }
}

public class product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Price { get; set; }
}

尝试将 (i,1) 更改为 [i]

var prodNames = from s in products
                where s.Name == products2[i]
                select s;

以及将其更改为 products2.Name。

从普通列表中选择和比较这些

//List<string> listA = new List<string>();

//  listA.Add("foobar");

工作得很好。

我在这里俯瞰什么?

标签: c#

解决方案


当您使用List<string>then时返回在子句product2[i]中使用的字符串,但是当您使用then 时,您需要使用或者更好的方法是使用循环来迭代列表并根据.WhereList<Product>product2[i].Nameforeachproducts2productsproduct2

public class Program
{
    public static void Main()
    {
        ..
     
        foreach(var product in product2)
        {

           //get all products whose name is same as product.Name
           var filteredProducts = products
               .Where(x => x.Name.Equals(product.Name)); //Instead of product2(i,1);

           foreach(var filtedProduct in filterProducts)
             Console.WriteLine(filteredProduct);
           ...
        }
    }
}

要打印产品详细信息,您可以override ToString()像在proudct课堂上一样工作,

//Use proper naming conventions, like class name starts with capital letter.
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Price { get; set; }

    public override string ToString()
    { 
        return $"{this.Id}, {this.Name} {this.Price + 641}";
    }   
}

推荐阅读