我对有效实施有疑问。假设我有两个数组:
One array is all possible items in a house: Table, Chair, TV, Fireplace, Bed The other is an array of items in a particular house: Table, TV, Bed
我还有两个列表框:
1. listbox for items in the house - the "HAS" list box 2. listbox items not in the house - the "NEEDS" list box
我需要在“HAS”列表框中列出房子中已有的项目以及“需要”列表框中不在房屋中的项目。在我看来,嵌套的“For each”循环将是解决这个问题的开始,但我不确定哪种情况需要嵌套。完成这样的任务的最有效方法是什么?
答案 0 :(得分:3)
var allItems = (new [] {"Table", "Chair", "TV", "Fireplace", "Bed"});
var hasItems = (new [] {"Table", "Chair"});
var hasList = hasItems.ToList();
var needsList = allItems.Except(hasItems).ToList();
答案 1 :(得分:1)
var allList = (new [] {"Table", "Chair", "TV", "Fireplace", "Bed"}).ToList();
var hasList = (new [] {"Table", "Chair"}).ToList();
var hasSet = new HashSet<string>(hasList);
var needsList = allList.Where(i => !hasList.Contains(i)).ToList();
这是最快的解决方案(至少在big O notation中)。