I have this piece of code that seems to support switching many list arguments into it, and it will compare each of them with each other to find a common list among all the other lists at the same time.
I cannot figure out how to pass multiple lists into a single argument, which is IEnmerable.
Say my test code looks like
List<uint> List1 = new List<uint>();
List<uint> List2 = new List<uint>();
List<uint> List3 = new List<uint>();
List<uint> Commons = FindCommon(List1, List2, List3);
List<uint> Commons = FindCommon<List<uint>>(List1, List2, List3);
What is the right name for this? Should I combine them somehow in IEnumerable ?? or should I somehow merge them all into a 1 list, but keeping some invisible separator?
static List<T> FindCommon<T>(IEnumerable<List<T>> lists)
{
Dictionary<T, int> map = new Dictionary<T, int>();
int listCount = 0;
foreach (IEnumerable<T> list in lists)
{
listCount++;
foreach (T item in list)
{
int currCount;
if (!map.TryGetValue(item, out currCount))
currCount = 0;
currCount++;
map[item] = currCount;
}
}
List<T> result= new List<T>();
foreach (KeyValuePair<T,int> kvp in map)
{
if (kvp.Value == listCount)
result.Add(kvp.Key);
}
return result;
}
PS > FindCommon , , , , , . , , .. , .
, .
public static List<T> FindCommon<T>(params List<T>[] lists)
{
SortedDictionary<T, bool>
current_common = new SortedDictionary<T, bool>(),
common = new SortedDictionary<T, bool>();
foreach (List<T> list in lists)
{
if (current_common.Count == 0)
{
foreach (T item in list)
{
common[item] = true;
}
}
else
{
foreach (T item in list)
{
if (current_common.ContainsKey(item))
{
common[item] = true;
}
}
}
if (common.Count == 0)
{
current_common.Clear();
break;
}
SortedDictionary<T, bool>
swap = current_common;
current_common = common;
common = swap;
common.Clear();
}
return new List<T>(current_common.Keys);
}