我想创建一个Linq-Extension来区分并在一个方法中过滤我的User
个对象:
public static List<User> FilterDistinct<TKey>(this IEnumerable<User> source, Func<User, TKey> key)
{
return source.Where(x => key(x) != null && key(x).ToString() != string.Empty).Select(x => key(x)).Distinct().ToList();
}
通话应该看起来像userList.FilterDistinct(x => x.LastName)
但我的代码中仍然存在语法错误,我无法弄明白。
错误:
无法将类型'System.Collections.Generic.List'隐式转换为'System.Collections.Generic.List'
答案 0 :(得分:3)
从您的LINQ查询返回的内容将是List<TKey>
类型 - 即,您从原始列表中使用Func<User,TKey>
到Select
。
但是,在扩展方法的正文中,您已经说过它将返回List<User>
。
因此,您传入的函数只是从您的用户中提取LastName
并返回一个不同的列表。您的预期返回时间为List<string>
而不是List<User>
。
答案 1 :(得分:2)
IMO,@ tym32167的回答打破了期望的行为,因为您需要export class MyItem {
public name: string;
public surname: string;
public category: string;
public address: string;
constructor();
constructor(name:string, surname: string, category: string, address?: string);
constructor(name:string, surname: string, category: string, address?: string) {
this.name = name;
this.surname = surname;
this.category = category;
this.address = address;
}
}
作为输出。
您需要构建自定义List<User>
以在EqualityComparer<User>
个对象上调用Distinct
。像这样:
User
另一个选择是使用static class MyExtensions
{
private class UserByKeyComparer<TKey> : EqualityComparer<User>
{
private readonly Func<User, TKey> keySelector;
private readonly EqualityComparer<TKey> keyComparer;
public UserByKeyComparer(Func<User, TKey> keyFunc)
{
this.keySelector = keyFunc;
this.keyComparer = EqualityComparer<TKey>.Default;
}
public override bool Equals(User x, User y)
{
return keyComparer.Equals(keySelector(x), keySelector(y));
}
public override int GetHashCode(User obj)
{
return keyComparer.GetHashCode(keySelector(obj));
}
}
public static List<User> FilterDistinct<TKey>(this IEnumerable<User> source, Func<User, TKey> keySelector)
{
return source
.Where(x => keySelector(x) != null && keySelector(x).ToString() != string.Empty)
.Distinct(new UserByKeyComparer<TKey>(keySelector))
.ToList();
}
}
(但我认为它会慢一点):
GroupBy
答案 2 :(得分:-1)
尝试编辑方法的返回值。
public static List<TKey> FilterDistinct<TKey>(this IEnumerable<User> source, Func<User, TKey> key)
{
return source.Where(x => key(x) != null && key(x).ToString() != string.Empty).Select(x => key(x)).Distinct().ToList();
}