# 整理一下 System.Linq.Enumerable 类中的那些比较少用的方法

Linq 虽然用得多，但是里面有一些方法比较少用，因此整理一下。Enumerable 类的所有方法可以在 MSDN 上查阅到：https://msdn.microsoft.com/zh-cn/library/system.linq.enumerable.aspx

# Aggregate

### Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>)

{
int[] array = new[] { 1, 2, 3, 4, 5 };
int result = array.Aggregate((sum, i) => sum + i);
Console.WriteLine(result);
}
{
string[] array = new string[] { "hello", "world", "!" };
string result = array.Aggregate((combine, str) =>
{
return combine + " " + str;
});
Console.WriteLine(result);
}

### Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>)

{
int[] array = new[] { 1, 2, 3, 4, 5 };
long result = array.Aggregate(-1L, (sum, i) =>
{
return sum + i;
});
Console.WriteLine(result);
}

### Aggregate<TSource, TAccumulate, TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>, Func<TAccumulate, TResult>)

{
string[] array = new string[] { "hello", "world", "!" };
string result = array.Aggregate("start", (combine, str) =>
{
return combine + " " + str;
}, end => end.ToUpperInvariant());
Console.WriteLine(result);
}

{
string[] array = new string[] { "hello", "world", "!" };
string result = array.Aggregate("start", (combine, str) =>
{
return combine + " " + str;
}).ToUpperInvariant();
Console.WriteLine(result);
}

# Except

### Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

A 序列减去 B 序列，并且去重了。

Key 会根据第一次匹配到的值。

# Join

### Join<TOuter, TInner, TKey, TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter, TKey>, Func<TInner, TKey>, Func<TOuter, TInner, TResult>)

List<Person> list1 = new List<Person>()
{
new Person()
{
Id = 1,
Gender = "M"
},
new Person()
{
Id = 2 ,
Gender = "F"
},
new Person()
{
Id = 3,
Gender = "M"
}
};
List<Student> list2 = new List<Student>()
{
new Student()
{
Id = 1,
Name = "martin"
},
new Student()
{
Id = 2,
Name = "valid void"
},
new Student()
{
Id = 4,
Name = "justin"
}
};

# GroupJoin

### GroupJoin<TOuter, TInner, TKey, TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter, TKey>, Func<TInner, TKey>, Func<TOuter, IEnumerable<TInner>, TResult>)

var result = (from person in list1
join student in list2 on person.Id equals student.Id into studentGroup
select new
{
Id = person.Id,
Gender = person.Gender,
Students = studentGroup.ToList()
}).ToList();

# SelectMany

### SelectMany<TSource, TResult>(IEnumerable<TSource>, Func<TSource, Int32, IEnumerable<TResult>>)

Func 多了个 Int32 的参数，看测试代码

# SkipWhile

Skip 倒是一直在用，SkipWhile 就用得比较少，也记录一下吧。

# ToLookup

### ToLookup<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>)

ILookup<int, Person> 这个的结构类似于一个数组，然后每个数组的元素是一个 Group。

# Zip

### Zip<TFirst, TSecond, TResult>(IEnumerable<TFirst>, IEnumerable<TSecond>, Func<TFirst, TSecond, TResult>)

posted @ 2018-04-10 15:27 h82258652 阅读(...) 评论(...) 编辑 收藏