|
|
using System;
|
|
|
using System.Collections.Generic;
|
|
|
using System.Text;
|
|
|
using System.Linq;
|
|
|
using System.Linq.Expressions;
|
|
|
|
|
|
using Xunit;
|
|
|
|
|
|
namespace LinqStudy.Test.LinqToObject
|
|
|
{
|
|
|
public class TakeTest
|
|
|
{
|
|
|
[Fact]
|
|
|
public void TakeWhile_Test()
|
|
|
{
|
|
|
List<Person> customers = new List<Person> {
|
|
|
new Person { Id=1,Name="woody1"},
|
|
|
new Person { Id=2,Name="woody2"},
|
|
|
new Person { Id=3,Name="woody3"},
|
|
|
new Person { Id=4,Name="woody1"}
|
|
|
};
|
|
|
|
|
|
var person = customers.TakeWhile(c => c.Name.StartsWith("woody1"));
|
|
|
|
|
|
//因为匹配第二项时,结果是False,程序返回,不再进行下次迭代,所以返回集合中只有第一项。
|
|
|
Assert.Equal(customers.FindAll(q => q.Id == 1), person); }
|
|
|
|
|
|
[Fact]
|
|
|
public void Test()
|
|
|
{
|
|
|
List<Person> customers = new List<Person> {
|
|
|
new Person { Id=1,Name="woody1"},
|
|
|
new Person { Id=2,Name="woody2"},
|
|
|
new Person { Id=3,Name="woody3"},
|
|
|
new Person { Id=4,Name="woody1"}
|
|
|
};
|
|
|
|
|
|
var person = customers.TakeWhile(c => c.Name.StartsWith("woody2"));
|
|
|
|
|
|
//因为匹配第一项时,结果是False,程序直接返回,不再进行下次迭代,所以返回空集合。
|
|
|
Assert.Empty(person);
|
|
|
}
|
|
|
|
|
|
[Fact]
|
|
|
public void Test_0()
|
|
|
{
|
|
|
List<Person> perons1 = new List<Person> {
|
|
|
new Person { Id=1,Name="woody1"},
|
|
|
new Person { Id=2,Name="woody2"},
|
|
|
new Person { Id=3,Name="woody3"},
|
|
|
new Person { Id=4,Name="woody4"},
|
|
|
};
|
|
|
|
|
|
List<Person> perons2 = new List<Person> {
|
|
|
new Person { Id=3,Name="woody3"},
|
|
|
new Person { Id=4,Name="woody1"},
|
|
|
new Person { Id=5,Name="woody5"},
|
|
|
new Person { Id=6,Name="woody6"},
|
|
|
};
|
|
|
|
|
|
var person = perons1.Intersect(perons2).ToList();
|
|
|
|
|
|
//特别注意:引用对象比较是否同一个引用,虽然内容一样,但引用不一样,交集仍然为空集合。
|
|
|
Assert.Empty(person);
|
|
|
}
|
|
|
|
|
|
[Fact]
|
|
|
public void Test_1()
|
|
|
{
|
|
|
List<int> test1 = new List<int>() { 1, 2, 3, 4 };
|
|
|
List<int> test2 = new List<int>() { 3, 4, 5, 6 };
|
|
|
|
|
|
var person = test1.Intersect(test2).ToList();
|
|
|
|
|
|
//特别注意:值对象,比较值本身。
|
|
|
Assert.Equal(2, person.Count);
|
|
|
}
|
|
|
|
|
|
[Fact]
|
|
|
public void Test_3()
|
|
|
{
|
|
|
List<Person> perons1 = new List<Person> {
|
|
|
new Person { Id=1,Name="woody1"},
|
|
|
new Person { Id=2,Name="woody2"},
|
|
|
new Person { Id=3,Name="woody3"},
|
|
|
new Person { Id=4,Name="woody4"},
|
|
|
};
|
|
|
|
|
|
List<Person> perons2 = new List<Person> {
|
|
|
new Person { Id=3,Name="woody3"},
|
|
|
new Person { Id=4,Name="woody4"},
|
|
|
new Person { Id=5,Name="woody5"},
|
|
|
new Person { Id=6,Name="woody6"},
|
|
|
};
|
|
|
|
|
|
perons1.AddRange(perons2);
|
|
|
|
|
|
var cc= perons1.Distinct().ToList();
|
|
|
Assert.Equal(8,cc.Count);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
}
|