查询对象的LINQ后如何在C#4.0中将类型强制转换为特定类 [英] How to cast a type to specific class in c# 4.0 after querying LINQ to Object

查看:106
本文介绍了查询对象的LINQ后如何在C#4.0中将类型强制转换为特定类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个客户列表,后来我查询该客户列表,以根据国家/地区代码提取一个客户数据.如何轻松实现此任务.这是我的代码段

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

此行显示错误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.

谢谢

推荐答案

使用.FirstOrDefault()获取与您的Where()匹配的第一个元素;如果没有匹配项,则使用null:

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.

这篇关于查询对象的LINQ后如何在C#4.0中将类型强制转换为特定类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆