I have this code in web forms:
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;
}
}
}
}
}
When I compile this code I get the error
Extension method must be defined in a non-generic static class.
My question is
Add new static
class and define your extension methods inside it. Check out MSDN documentation for Extension methods.
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;
}
}
}
}
}
Add your method into static
class for extension method in this way
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;
}
}
}
}
}
Now use it
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);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.