区分,但忽略空/空

  • 本文关键字:区分 c# linq morelinq
  • 更新时间 :
  • 英文 :


我有一个电影列表,我需要将它们与另一个列表合并并复制。

我正在使用 Jon Skeet 的DistinctBy(m => m.SomeUniqueMovieProperty)来实现这一点,它工作正常。 除了,我们很快发现,在某些情况下,10-20% 的电影(在任一列表中)都没有填写此属性,导致DistinctBy将它们折叠成 1 部幸运电影。

这是一个问题,我们希望保留所有没有此属性值的电影。最初我想从每个集合中提取这些电影,复制,然后再次合并它们,有没有更短的解决方案来解决这个问题?

DistinctBy()的结果与Where([null or empty]).的结果连接

起来
var nullMovies = allMovies.Where(m=>string.IsNullOrEmpty(m.SomeUniqueMovieProperty));
var distinctNonNullMovies = allMovies.Where(m => !string.IsNullOrEmpty(m.SomeUniqueMovieProperty)).DistinctBy(m => m.SomeUniqueMovieProperty);
var result = nullMovies.Concat(distinctNonNullMovies);

假设mEquals/GetHashCode没有被覆盖,如果m.SomeUniqueMoviePropertynull并且你没有任何其他唯一键,你可以使用m本身作为唯一键。

DistinctBy(m => (object) m.SomeUniqueMovieProperty ?? m)

如果要包含所有 null,则需要将 null 属性替换为在 null 时唯一的属性。假设该属性是一个字符串,Guid 将很好地完成这项工作。

.DistinctBy(m => m.SomeUniqueMovieProperty ?? Guid.NewGuid().ToString())

每当它命中具有 null 值的属性时,都会使用随机的新 guid 值填充它。


如果您还希望空标题不被删除,请将查询更改为

.DistinctBy(m => String.IsNullOrEmpty(m.SomeUniqueMovieProperty) ? Guid.NewGuid().ToString() : m.SomeUniqueMovieProperty)

另一种选择是制作自己的DistinctBy,按照您想要的方式运行。这是原始源的调整版本,仅在返回 true 时才应用过滤器shouldApplyFilter为简洁起见,注释也会被删除。

static partial class MoreEnumerable
{
public static IEnumerable<TSource> ConditionalDistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, Func<TKey, bool> shouldApplyFilter)
{
return source.ConditionalDistinctBy(keySelector, shouldApplyFilter, null);
}
public static IEnumerable<TSource> ConditionalDistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, Func<TKey, bool> shouldApplyFilter, IEqualityComparer<TKey> comparer)
{
if (source == null) throw new ArgumentNullException("source");
if (keySelector == null) throw new ArgumentNullException("keySelector");
if (shouldApplyFilter == null) throw new ArgumentNullException("shouldApplyFilter");
return ConditionalDistinctByImpl(source, keySelector, shouldApplyFilter, comparer);
}
private static IEnumerable<TSource> ConditionalDistinctByImpl<TSource, TKey>(IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, Func<TKey, bool> shouldApplyFilter, IEqualityComparer<TKey> comparer)
{
var knownKeys = new HashSet<TKey>(comparer);
foreach (var element in source)
{
var key = keySelector(element);
if (shouldApplyFilter(key) && knownKeys.Add(key))
{
yield return element;
}
}
}
}

它会像

.ConditionalDistinctBy(m => m.SomeUniqueMovieProperty, s => !String.IsNullOrEmpty(s));

也许您可以在复合非重复键上过滤它们,如下所示

movies.DistinctBy(m => String.Format({0}{1}{...},m.prop1,m.prop2,[]));

最后一种方法,可能是矫枉过正,你可以实现IEqualityComparer,如果null被认为是唯一的,你可以把逻辑放在那里。 DistinctBy 对于这种情况来说是一个重载。

public class MovieComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
if (x == null || y == null)
{
return false;
}
return x == y;
}
public int GetHashCode(string obj)
{
if (obj == null)
{
return 0;
}
return obj.GetHashCode();
}
}