Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

list - How to cast a type to specific class in c# 4.0 after querying LINQ to Object

i have a list of customer and later i query that list of customer to extract one customer data based on country code. how to achieve easily this task. here is my code snippet

public class Customer
{
        public string Name
        { get; set; }

        public double Salary
        { get; set; }

        public string CountryCode
        { get; set; }
}

private void button1_Click(object sender, EventArgs e)
{
            List<Customer> oCust = new List<Customer>();
            oCust.Add(new Customer { Name = "Tridip", Salary = 200, CountryCode = "GB" });
            oCust.Add(new Customer { Name = "Ari", Salary = 200, CountryCode = "US" });
            oCust.Add(new Customer { Name = "Dib", Salary = 200, CountryCode = "CA" });

            Customer oCustomer = oCust.Where(x => x.CountryCode == "US");
}

this line is giving error Customer oCustomer = oCust.Where(x => x.CountryCode == "US");

i could follow this below approach to solve it

    var oCustomer = oCust.Where(x => x.CountryCode == "US");

    foreach (var item in oCustomer)
    {
        Customer _Cust = new Customer();
        _Cust.Name = item.Name;
        _Cust.Salary = item.Salary;
        _Cust.CountryCode = item.CountryCode;
    }

but i like to know is there any other way around to get one customer data after querying list. please let me know with sample code. also discuss how to solve the above scenario using auto mapper with sample code.

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use .FirstOrDefault() to get the first element matching your Where(), or null when none match:

var oCustomer = oCust.Where(x => x.CountryCode == "US").FirstOrDefault();

also discuss how to solve the above scenario using auto mapper with sample code.

You've done this under various of your questions: "Here is my question, oh and please explain this related concept to me with sample code".

This is not how Stack Overflow works. Search the web for automapper, find their Getting Started page and ask a new question if you can't figure out how to use it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...