How C # Converts list of object to list of T concrete types

Source: Internet
Author: User

Last week the code encountered a problem, because of design constraints, a method accepts parameters only list<object> type, but the method needs to deal with the real data is determined list<currency>. However, C # does not allow a direct conversion type to be displayed and is not operable in two directions. The problem blew me off for a while, and finally, on MSDN, I found a oftype<t> way to do it.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;namespaceconsoleapplication1{Internal classProgram {Private Static voidMain (string[] args) {List<Object> Currencylistoftype =Newlist<Object>()            {                NewCurrency () {Id = Guid.NewGuid (), Name ="a"},                NewCurrency () {Id = Guid.NewGuid (), Name ="b"},                NewCurrency () {Id = Guid.NewGuid (), Name ="C"}            }; List<Object> currencylistcast =Newlist<Object>()            {                "a","b","C"            }; //=>oftype If the element is not converted, the exception is not present, only the successful element is converted, or the list is empty if the currencies is not converted, NOT NULLList<currency> currencies = currencylistoftype.oftype<currency>().            ToList (); //=>cast If the element cannot be converted, it will fail. list<currency> currencies1 = currencylistcast.cast<currency>().            ToList (); Console.WriteLine ("Currencies List:"); foreach(varIteminchcurrencies) {Console.WriteLine (item.            ID); } Console.WriteLine ("currencies1 list:"); foreach(varIteminchcurrencies1) {Console.WriteLine (item.            ID);        } console.readline (); }    }     Public classCurrency { PublicGuid Id {Get;Set; }  Public stringName {Get;Set; } }}

How C # Converts list of object to list of T concrete types

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.