如何从2个相似的列表中选择每个<> [英] How can I select each from 2 similar list<>
问题描述
我有两个不同的List<>来自下面给出的Foood类。
如何从每个列表中选择:
x1.calories + x2.calories<可以满足CertainValue
吗?
我尝试了什么:
公共类Foood
{
public string Name {get;组; }
公共双卡路里{get;组; }
public Foood(字符串名称,双卡路里)
{
this.Name = name;
this.calories = calory;
}
}
您好,
您的查询:ListX1.Where(X1 = > ListX2.Any(X1 = > X1.b == X2.b))
正在检查ListX2中的ListX2中是否存在值,但是没有列表的连接。
列表的Concat如何 Enumerable .Concat(TSource)方法(IEnumerable(TSource),IEnumerable(TSource))(System.Linq) [ ^ ]
var list = ListX1.Concat(ListX2);
您还可以采用其他方式,例如使用AddRange List(T).AddRange方法(IEnumerable(T))(System.Collections.Generic) [< a href =https://msdn.microsoft.com/en-us/library/z883w3dc(v=vs.110).aspx\"target =_ blanktitle =New Window> ^ ]
var list = new 列表< Foood> ;();
list.AddRange(ListX1);
list.AddRange(ListX2);
然后
list = list.Where(x = > x.calories < CertainValue)。ToList();
编辑1
以上可能不是您所需要的,所以提到加入列表
var joinedLists =(来自 x1 ListX1
join x2 中的code-keyword> x1.b上的ListX2
等于x2.b // 这是两个列表的连接
其中 x1.calories + x2.calories < certainValue // where condition
select new
{
x1.Name,
x1.calori es,
x2.Name
x2.calories
})。ToList(); // 项目进入新的匿名类型列表并选择必填字段
I have two different List<> from the Foood class given below. How can I select from each list such that : x1.calories + x2.calories < CertainValue can be satisfied?
What I have tried:
public class Foood { public string Name { get; set; } public double calories { get; set; } public Foood(string name, double calory) { this.Name = name; this.calories = calory; } }
Hi,
Your query:ListX1.Where(X1 => ListX2.Any(X1 => X1.b == X2.b))
is checking if values from ListX2 exist in ListX1 but there's no joining of lists.
How about the Concat of lists Enumerable.Concat(TSource) Method (IEnumerable(TSource), IEnumerable(TSource)) (System.Linq)[^]
var list = ListX1.Concat(ListX2);
Also you can do another way like using AddRange List(T).AddRange Method (IEnumerable(T)) (System.Collections.Generic)[^]
var list = new List<Foood>(); list.AddRange(ListX1); list.AddRange(ListX2);
Then
list = list.Where(x => x.calories < certainValue).ToList();
Edit 1
The above may not be what you require, so by mentioning joining of lists
var joinedLists = (from x1 in ListX1 join x2 in ListX2 on x1.b equals x2.b //this is joining of both lists where x1.calories + x2.calories < certainValue //where condition select new { x1.Name, x1.calories, x2.Name x2.calories }).ToList(); //project into new list of anonymous type and select the required fields
这篇关于如何从2个相似的列表中选择每个<>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!