当前位置: 移动技术网 > IT编程>开发语言>c# > Linq扩展方法

Linq扩展方法

2020年03月09日  | 移动技术网IT编程  | 我要评论

如果要扩展linq查询方法集,只需要为ienumerable<t>扩展方法。

第一种:扩展聚合方法,类似已有的max、min,可以给具体类型扩展,也可以给泛型扩展。

using system;
using system.collections;
using system.collections.generic;
using system.data;
using system.io;
using system.linq;

namespace consoleapp4
{
    class program
    {
        static void main(string[] args)
        {
            var numbers1 = new double[]{ 1.9, 2, 8, 4, 5.7, 6, 7.2, 0 };

            var query1 = numbers1.median();

            console.writeline("double: median = " + query1);
            
            var numbers2 = new int[] { 4, 5, 6, 8, 0 };
            var query2 = numbers2.median();

            console.writeline($"int:median ={query2}");

            var str1 = new string[] { "ab", "abc", "abcde", "abcedfs" }; ;
            var query3 = str1.median(x => x.length);

            console.writeline($"string:{query3}");
        }
     
    }

    public static class linqextension
    {
        public static double median(this ienumerable<double> source)
        {
            if(source.count()==0)
            {
                throw new invalidoperationexception("无法计算中位数");
            }

            var sortedlist = source.orderby(x => x);

            int itemindex = (int)sortedlist.count()/2;

            // 索引从0开始,itemindex总是偏大
            if(sortedlist.count()%2==0)
            {
                return (sortedlist.elementat(itemindex) + sortedlist.elementat(itemindex - 1)) / 2;
            }
            else
            {
                return sortedlist.elementat(itemindex);
            }
        }
       
        //int类型重载求中位数
        public static double median(this ienumerable<int> source)
        {            
            return source.select(x => convert.todouble(x)).median();           
        }

        //泛型,需传入选择器
        public static double median<t>(this ienumerable<t> source,func<t,double> selector)
        {
            return source.select(x => selector(x)).median();
        }       
    }    
}

第二中:扩展返回集合的方法,类似where、orderby

 public static class linqextension
    {
        public static ienumerable<t> alternateelements<t>(this ienumerable<t> source)
        {
            list<t> list = new list<t>();

            int i = 0;

            foreach (var item in source)
            {
                if (i % 4 == 2)
                {
                    list.add(item);
                }
            }
            return list;           
        }
    }

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网