c# - 将列表与另一个列表进行比较并获取匹配项
问题描述
不确定我是否忽略了某些东西,但又是早上 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");
工作得很好。
我在这里俯瞰什么?
解决方案
当您使用List<string>
then时返回在子句product2[i]
中使用的字符串,但是当您使用then 时,您需要使用或者更好的方法是使用循环来迭代列表并根据.Where
List<Product>
product2[i].Name
foreach
products2
products
product2
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}";
}
}
推荐阅读
- excel - 插入带除法的简单公式时出现运行时错误 1004
- javascript - dygraphs.js 和 dygraphs.min.js 之间的行为差异
- c# - 反序列化没有节点名称的 JSON
- docker - 寻找关于 containerd-shim/runc 子进程的解释
- c# - 静态方法不会改变引用类型
- raspberry-pi3 - 如何使用 Raspberry Pi3 读取 SunRom 血压传感器数据
- html - 尝试将组件添加到模块文件时,Stackblitz 上的导入错误
- javascript - 离开视口后从表单元素中移除键盘焦点
- c# - 在 xamarin.form 我们如何使用 xamarin.form 发送短信?
- python - Pandas - 对每个子集应用转换(在 n 列中选择)