You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
3.3 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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);
}
}
}