我正在尝试创建一个包装器,用于从单个阵列中选择多个项目。我在下面的代码结尾处得到了结果。不知道我做错了什么。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Tester.cs
{
class Program
{
static void Main(string[] args)
{
var customers = new[]
{
new { CustomerID = 1, FirstName = "Orlando", LastName = "Gee",
CompanyName = "A Bike Store" },
new { CustomerID = 2, FirstName = "Keith", LastName = "Harris",
CompanyName = "Bike World" },
new { CustomerID = 3, FirstName = "Donna", LastName = "Carreras",
CompanyName = "A Bike Store" },
new { CustomerID = 4, FirstName = "Janet", LastName = "Gates",
CompanyName = "Fitness Hotel" },
new { CustomerID = 5, FirstName = "Lucy", LastName = "Harrington",
CompanyName = "Grand Industries" },
new { CustomerID = 6, FirstName = "David", LastName = "Liu",
CompanyName = "Bike World" },
new { CustomerID = 7, FirstName = "Donald", LastName = "Blanton",
CompanyName = "Grand Industries" },
new { CustomerID = 8, FirstName = "Jackie", LastName = "Blackwell",
CompanyName = "Fitness Hotel" },
new { CustomerID = 9, FirstName = "Elsa", LastName = "Leavitt",
CompanyName = "Grand Industries" },
new { CustomerID = 10, FirstName = "Eric", LastName = "Lang",
CompanyName = "Distant Inn" }
};
var addresses = new[] {
new { CompanyName = "A Bike Store", City = "New York", Country = "United States"},
new { CompanyName = "Bike World", City = "Chicago", Country = "United States"},
new { CompanyName = "Fitness Hotel", City = "Ottawa", Country = "Canada"},
new { CompanyName = "Grand Industries", City = "London", Country = "United Kingdom"},
new { CompanyName = "Distant Inn", City = "Tetbury", Country = "United Kingdom"}
};
IEnumerable<Names> customerfullName = customers.Select(data => new Names {
FirstName = data.FirstName,
LastName = data.LastName});
foreach (Names entry in customerfullName)
{
Console.WriteLine(entry);
}
}
}
class Names
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
Tester.cs.Names是我在运行程序时重复的内容。
答案 0 :(得分:1)
Console.WriteLine
使用ToString
类的object
方法。默认情况下,它显示类的名称。
此方法被派生自object
的类重写,以显示他们想要的内容。你没有覆盖它,所以你得到了默认值。
您可以在没有LINQ的情况下重现您的问题,如下所示:
class Names
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
var name = new Names {FirstName = "John", LastName = "Saunders"};
Console.WriteLine(name); // Will display "Tester.cs.Names"
答案 1 :(得分:0)
您的Names
类没有覆盖ToString
方法,因此它使用object
中的默认实现并打印出它的类型名称。您需要覆盖ToString
中的Names
以打印出基础字符串,或者需要在foreach
循环中打印出各个字符串属性。
答案 2 :(得分:0)
默认使用ToString,使用:
class Names
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
还可以为全名
创建额外的属性class Names
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
}
用法:
foreach (Names entry in customerfullName)
{
Console.WriteLine(entry.FullName);
}