List<string> difference tool for two input List<string> listA and listB
Output List<string>
- both - in both listA and listB
- listAonly - in listA only
- listBonly - in listB only
Looking for speed, space, and style
.
//test
List<string> both;
List<string> both;
List<string> listAonly;
List<string> listBonly;
ListDiff( new List<string>() { "AAA", "BBB", "CCC", "DDD", "GGG", "FFF", "BBB", "GGG" }
, new List<string>() { "AAA", "BBB", "DDD", "FFF", "EEE", "FFF", "EEE" }
, false, out both, out listAonly, out listBonly );
Debug.WriteLine("both");
foreach (string s in both)
Debug.WriteLine($" {s}");
Debug.WriteLine("listAonly");
foreach (string s in listAonly)
Debug.WriteLine($" {s}");
Debug.WriteLine("listBonly");
foreach (string s in listBonly)
Debug.WriteLine($" {s}");
//end test
public static void ListDiff(List<string> listA, List<string> listB, bool ignoreCase, out List<string> both, out List<string> listAonly, out List<string> listBonly)
{
both = new List<string>();
listAonly = new List<string>();
listBonly = new List<string>();
IEnumerable<string> listAsorted = listA.OrderBy(x => x).Distinct();
IEnumerable<string> listBsorted = listB.OrderBy(x => x).Distinct();
var listAenumerator = listAsorted.GetEnumerator();
var listBenumerator = listBsorted.GetEnumerator();
bool listAcanmove = listAenumerator.MoveNext();
bool listBcanmove = listBenumerator.MoveNext();
while (listAcanmove | listBcanmove)
{
string valueA = listAenumerator.Current;
string valueB = listBenumerator.Current;
//Debug.WriteLine($"valueA = {valueA}");
//Debug.WriteLine($"valueB = {valueB}");
if (!listAcanmove && listBcanmove)
{
//Debug.WriteLine($"{valueB} in B not in A");
listBonly.Add(valueB);
listBcanmove = listBenumerator.MoveNext();
}
if (listAcanmove && !listBcanmove)
{
//Debug.WriteLine($"{valueA} in A not in B");
listAonly.Add(valueA);
listAcanmove = listAenumerator.MoveNext();
}
else
{
int comp = string.Compare(valueA, valueB, ignoreCase);
if (comp == -1)
{
//Debug.WriteLine($"{valueA} in A not in B");
listAonly.Add(valueA);
listAcanmove = listAenumerator.MoveNext();
}
else if (comp == 1)
{
//Debug.WriteLine($"{valueB} in B not in A");
listBonly.Add(valueB);
listBcanmove = listBenumerator.MoveNext();
}
else
{
//Debug.WriteLine($"{valueA} {valueB} in B and A");
both.Add(valueA);
listAcanmove = listAenumerator.MoveNext();
listBcanmove = listBenumerator.MoveNext();
}
}
//Debug.WriteLine("");
}
//Debug.WriteLine($"done");
}