课程地址 : http://www.sikiedu.com/my/course/293
凉鞋大大的,可以的话大家多支持一波~
一.OfType
功能 :根据指定类型筛选 IEnumerable 的元素。
1.linq
public class LINQOfTypeExample : MonoBehaviour
{
void Start()
{
var infos = new ArrayList() { 1, 2, 3, 4, 5, "6", 7.0, 8.0f };
infos.OfType<float>()
.ToList()
.ForEach(info => Debug.Log(info));
}
}
2.UniRx
public class UniRxOfTypeExample : MonoBehaviour
{
public class Enemy { public string Name { get; set; } };
public class Boss : Enemy { };
public class Monster : Enemy { };
void Start()
{
var subject = new Subject<Enemy>();
subject
.OfType<Enemy, Boss>()
.Subscribe(boss =>
{
Debug.Log(boss.Name);
});
subject.OnNext(new Boss { Name = "蘑菇王" });
subject.OnNext(new Monster { Name = "蘑菇" });
subject.OnNext(new Boss { Name = "阿龙" });
subject.OnCompleted();
}
}
输出 :
二.Cast
功能 : 将 IEnumerable 的元素强制转换为指定的类型。
1.linq
public class LINQCastExample : MonoBehaviour
{
private void Start()
{
var infos = new List<object> { "lemon", "apple", "melon" };
infos.Cast<string>()
.ToList()
.ForEach(fruit => Debug.Log(fruit));
}
}
2.UniRx
public class UniRxCastExample : MonoBehaviour
{
// Use this for initialization
void Start()
{
var subject = new Subject<object>();
subject.Cast<object, string>()
.Subscribe(value => Debug.Log(value), e =>
{
Debug.Log("has exception");
Debug.LogException(e);
});
subject.OnNext("123123");
subject.OnNext("123123");
subject.OnNext(123);
subject.OnCompleted();
}
}
输出 :
可以看到,当转换类型出错时会执行注册的函数
三. GroupBy
功能 :对序列中的元素进⾏分组。
1.linq
public class LINQGroupByExample : MonoBehaviour
{
class Student
{
public string Name;
public int Age;
}
void Start()
{
var students = new List<Student>() {
new Student(){Name="张三",Age=18},
new Student(){Name="asd",Age=19},
new Student(){Name="zxc",Age=120},
new Student(){Name="qwe",Age=20},
new Student(){Name="123",Age=18},
new Student(){Name="aaa",Age=120},
new Student(){Name="bbb",Age=19},
};
students.GroupBy(student => student.Age)
.ToList()
.ForEach(studentGroup =>
{
studentGroup
.ToList()
.ForEach(student =>
{
Debug.LogFormat("GroupName:{0} Name:{1} Age:{2}", studentGroup.Key, student.Name, student.Age);
});
});
}
}
2.UniRx
public class UniRxGroupByExample : MonoBehaviour
{
void Start()
{
var subject = new Subject<int>();
subject.GroupBy(number => number % 2 == 0 ? "偶数" : "奇数")
.Subscribe(numberGroup =>
{
numberGroup.Subscribe(number =>
{
Debug.LogFormat("GroupKey:{0} Number:{1}", numberGroup.Key, number);
});
});
subject.OnNext(10);
subject.OnNext(4);
subject.OnNext(3);
subject.OnNext(2);
subject.OnNext(5);
subject.OnCompleted();
}
}
输出:
四.Range
功能 :⽣成指定范围内的整数的序列。
1.linq
public class LINQRangeExample : MonoBehaviour
{
void Start()
{
Enumerable.Range(5, 10).Select(x => x * x)
.ToList()
.ForEach(number =>
{
Debug.Log(number);
});
}
}
2.UniRx
public class UniRxRangeExample : MonoBehaviour
{
void Start()
{
Observable.Range(5, 10).Select(x => x * x)
.Subscribe(number =>
{
Debug.Log(number);
});
}
}
输出 :
注意不是输出5-10的平方,而是从5开始十个数的平方