Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method must be defined in a non-generic static class

Tags:

c#

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

  1. I cannot change this partial class to static. How will I accomplish the same without it?
like image 831
Venkat Avatar asked Nov 19 '25 14:11

Venkat


1 Answers

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;
                }
            }
        }
    }
 }
like image 88
Hari Prasad Avatar answered Nov 22 '25 04:11

Hari Prasad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!