What is the most efficient way to compare/sort items from two arrays?

被刻印的时光 ゝ 提交于 2020-01-24 00:25:16

问题


I have a question about efficient implementation. Lets say I have two arrays:

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

I also have two list boxes:

1. listbox for items in the house - the "HAS" list box
2. listbox items not in the house - the "NEEDS" list box

I need to list the items already in the house in the "HAS" list box as well as the items that are NOT in the house in the "NEEDS" list box. It seems to me that nested "For each" loops would be a start to solving this problem but I am not exactly sure which case needs to be nested. What is the most efficient way to accomplish a task like this?


回答1:


var allItems = (new [] {"Table", "Chair", "TV", "Fireplace", "Bed"});
var hasItems = (new [] {"Table", "Chair"});

var hasList = hasItems.ToList();
var needsList = allItems.Except(hasItems).ToList();



回答2:


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();

That's ~ the fastest solution (at least, in big O notation).



来源:https://stackoverflow.com/questions/1140220/what-is-the-most-efficient-way-to-compare-sort-items-from-two-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!