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
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 :
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.
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
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.