[英]C# Linq query to join two lists and assign the result to combobox
I have a two list of strings 我有两个字符串列表
Lista Listb
------------------------
apple mango
mango grapes
grapes watermelon
pineapple orange
banana
I want to show all the items of lista in my combobox also select items common to both in this case mango and grapes and pre-check them in the combobox 我想在组合框中显示lista的所有项目,还选择在这种情况下芒果和葡萄都通用的项目,并在组合框中进行预检查
combobox items
---------------------
apple
mango - checked
grapes - checked
pineapple
banana
The following should give you a list containing value from Lista
and additional information of whether an item in the list should be checked or not in IsChecked
property : 以下应为您提供一个包含
Lista
值的列表以及有关是否应在IsChecked
属性中检查列表中的项目的附加信息:
var result = Lista.Select(a => new
{
Value = a,
IsChecked = Listb.Any(b => b == a)
}).ToList();
The rest is simply binding the result to combobox. 剩下的只是将结果绑定到组合框。 This step varies depending on your platform (ASP.NET, WPF, Windows Form, etc. almost all has combobox), and each, I believe, is well-documented on the internet so you should read and try one first.
此步骤因您的平台(ASP.NET,WPF,Windows Form等,几乎都具有组合框)而异,并且,我相信每个元素在Internet上都有据可查,因此您应该首先阅读并尝试一个。
you can do 你可以做
var listA = new[] {"apple", "mango", "grapes", "pineapple", "banana"};
var listB = new[] {"mango", "grapes", "watermelon", "orange"};
var common = listA.Intersect(listB);
to get the overlap 得到重叠
Try Left join in Linq 尝试在Linq中加入Left
var listA = new[] { "apple", "mango", "grapes", "pineapple", "banana" }.ToList();
var listB = new[] { "mango", "grapes", "watermelon", "orange" }.ToList();
var listCheckboxItem =
(
from a in listA
join b in listB on a equals b into lst
from item in lst.DefaultIfEmpty()
select new
{
Name = a,
IsChecked = !(string.IsNullOrEmpty(item))
}
).ToList();
Select
can get a list of booleans showing which elements are in both lists. Select
可以获取一个布尔值列表,显示两个列表中都包含哪些元素。
List<string> Lista = new List<string>(new string[] { "apple", "mango", "grapes", "pineapple", "banana" });
List<string> Listb = new List<string>(new string[] {"mango","grapes","watermelon","orange"});
var inBoth = Lista.Select(x => Listb.Contains(x));
// False, True, True, False, False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.