创建一个自定义IEqualityComparer<IList<string>>
,您可以将其用于大多数 linq 方法,例如GroupBy
or Distinct
。请注意,它也适用于string[]
which implements IList<string>
:
public class IgnoreOrderComparer : IEqualityComparer<IList<string>>
{
public IgnoreOrderComparer(StringComparer comparer)
{
this.Comparer = comparer;
}
public StringComparer Comparer { get; set; }
public bool Equals(IList<string> x, IList<string> y)
{
if (x == null || y == null) return false;
// remove the Distincts if there are never duplicates as mentioned
return !x.Distinct(Comparer).Except(y.Distinct(Comparer), Comparer).Any();
// btw, this should work if the order matters:
// return x.SequenceEqual(y, Comparer);
}
public int GetHashCode(IList<string> arr)
{
if (arr == null) return int.MinValue;
int hash = 19;
foreach (string s in arr.Distinct(Comparer))
{
hash = hash + s.GetHashCode();
}
return hash;
}
}
然后,您可以使用以下查询来创建 dictinct SortedDictionary<string, List<string>>
。
样本数据:
SortedDictionary<string, List<string>> dict = new SortedDictionary<string, List<string>>();
dict.Add("A", new List<string>() { "A", "B" });
dict.Add("B", new List<string>() { "B", "B" });
dict.Add("C", new List<string>() { "A", "B" });
dict.Add("D", new List<string>() { "C", "E" });
dict.Add("E", new List<string>() { "E", "C" });
首先在列表上使用Distinct
,然后将它们与原始字典连接起来,最后创建一个新字典:
var comparer = new IgnoreOrderComparer(StringComparer.OrdinalIgnoreCase);
var uniqueLists = dict.Values.Distinct(comparer);
var uniqueDict = from list in uniqueLists
join kvp in dict
on list equals kvp.Value
select kvp;
dict = new SortedDictionary<string,List<string>>(uniqueDict.ToDictionary(kv => kv.Key, kv => kv.Value));
即使列表中字符串的顺序很重要,它也可能会有所帮助。