我在网络表单中有这个代码:
namespace TrendsTwitterati
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<TweetEntity> tweetEntity = tt.GetTweetEntity(1, "")
.DistinctBy(e => e.EntityPicURL);
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
}
}
编译此代码时,我收到错误
扩展方法必须在非泛型静态类中定义。
我的问题是
答案 0 :(得分:4)
添加新的static
类并在其中定义扩展方法。查看MSDN documentation的扩展方法。
namespace TrendsTwitterati
{
public partial class Default: System.Web.UI.Page
{
}
public static class MyExtensions
{
public static IEnumerable < TSource > DistinctBy < TSource, TKey > (this IEnumerable < TSource > source, Func < TSource, TKey > keySelector)
{
HashSet < TKey > seenKeys = new HashSet < TKey > ();
foreach(TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield
return element;
}
}
}
}
}
答案 1 :(得分:3)
以这种方式将您的方法添加到static
类中以获取扩展方法
namespace TrendsTwitterati
{
public static class Extension
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
}
}
现在使用它
namespace TrendsTwitterati
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<TweetEntity> tweetEntity = tt.GetTweetEntity(1, "").DistinctBy(e => e.EntityPicURL);
}
}
}