LINQ Notes -ToLookup (), OfType (), Cast (), DefaultIfEmpty () Case

ToLookup():

Providing a linq ToDictionary () extension method, converted into a type Dictionary

personList.ToLookup(p => p.CompanyID);

key is CompanyID, Value is the Person object. If CompanyID duplicate values, it will throw an exception. So with ToLookup

var dict = personList.ToLookup(p => p.CompanyID);

No exception is thrown, value is a collection.

 

OfType():

Screening of the specified type of element

List<object> objList = new List<object> {
            new Company() { ID = 1, Name = "阿里" },
            new Company() { ID = 2, Name = "百度" },
            new Person() { ID = 1, Name = "马云", CompanyID = 1 }
            };
            var p = objList.OfType<Person>().ToList();

 

DefaultIfEmpty():

DefaultIfEmpty action () method is that, if the set is empty, it returns a default type comprising a set of elements.

List <Company> = comList new new List <Company> {};
 var List = comList.DefaultIfEmpty () ToList ();.   // List only one null elements

 

Cast():

The cast element to the specified type, if it can not be converted Throws

List<Company> comList = new List<Company> {
            new Company() { ID = 1, Name = "阿里" },
            new Company() { ID = 2, Name = "百度" }
            };
            var l = comList.Cast<object>().ToList();

Guess you like

Origin www.cnblogs.com/fanfan-90/p/12114126.html