C# LINQ Return Generic List<T> - c#

Below are two classes I have sampled.
Without using tuple;
  I would like to send queries directly from the first list to the second list of results.
The part that fails in the encoding appears as convert operations.
I thank you for your time and reply.
static void Main(string[] args)
{
List<liste> personel = new List<liste>{
new liste { PersonId = 1, Name = "Burak", Surname = "Şenyurt", City = "İstanbul", Salary = 890 },
new liste { PersonId = 2, Name = "Maykıl", Surname = "Cordın", City = "Chicago", Salary = 930 },
new liste { PersonId = 3, Name = "Şakiyıl", Surname = "Oniyıl", City = "Los Angles", Salary = 986 },
new liste { PersonId = 4, Name = "Ümit", Surname = "Oniyıl", City = "Los Angles", Salary = 1035 },
new liste { PersonId = 5, Name = "Mehmet", Surname = "Zaferoğlu", City = "Los Angles", Salary = 1265 },
new liste { PersonId = 6, Name = "Hasan", Surname = "Orkun", City = "Los Angles", Salary = 1435 },
new liste { PersonId = 7, Name = "Raşit", Surname = "Mesut", City = "Los Angles", Salary = 1469 },
new liste { PersonId = 8, Name = "Hamdi", Surname = "Tanpınar", City = "Los Angles", Salary = 1535 },
new liste { PersonId = 9, Name = "Şevki", Surname = "Çapkın", City = "Los Angles", Salary = 1636 },
new liste { PersonId = 10, Name = "Özhun", Surname = "Bozkurt", City = "Los Angles", Salary = 1839 }
};
double resAVG = personel.Select(x => x.Salary).Average();
List<Sonuc> reportResult = GetReport(personel,resAVG);
}
Static Method
public static List<Sonuc> GetReport(List<liste> listePersonel , double resAVG)
{
List<Sonuc> result = (from e in listePersonel
where e.Salary >= resAVG
orderby e.Salary descending
//select new Tuple<string, string, double>(e.Name, e.Surname, e.Salary)).ToList<Tuple<string, string, double>>();
select new List<Sonuc>(e.Name, e.Surname, e.Salary)).ToList<Sonuc>(result.ToList());
return result;
}
General Class
public class liste
{
public int PersonId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string City { get; set; }
public double Salary { get; set; }
public override string ToString()
{
return $"PersonId : {PersonId}\t\tName , Surname {Name} , {Surname}\t\t\tSalary : {Salary}";
}
}
Result Class
public class Sonuc
{
public string Name { get; set; }
public string Surname { get; set; }
public double Salary { get; set; }
public Sonuc(string Name , string Surname, double Salary)
{
this.Name = Name;
this.Surname = Surname;
this.Salary = Salary;
}
public override string ToString()
{
return $"Name, SurName : {this.Name} , {this.Surname}\t\t\tSalary : {this.Salary}";
}
}

You're trying to construct an instance of List<T> by passing it a string, a string, and a double. List<T> does not have a constructor which takes these parameters. Also, you can't use result before you've assigned it.
Instead, you should project each item in listePersonel to a single instance of Sounc, then take that enumerable to a List<Sounc>.
public static List<Sonuc> GetReport(List<liste> listePersonel , double resAVG)
{
List<Sonuc> result = (from e in listePersonel
where e.Salary >= resAVG
orderby e.Salary descending
select new Sonuc(e.Name, e.Surname, e.Salary)).ToList();
return result;
}

Related

Join 2 collection list together from 2 data sources find the matches and loop through the results

I am wanting to merge together 2 different collections.
Example collection 1: (linqpad to live sql server)
Sample Data (collection azedIdentity):
PersonID | FirstName | LastName |
3197908 John Smith
4444 Jody Smith
55555 Jon Smither
var azedIdentity = PersonMatchNoDOBRequired("John", "Smith").AsDynamic()
.Select (x => new FindPersonContactViewModel
{
PersonID = x.PersonID,
AZEDID = x.AZEDID,
FirstName = x.FirstName,
MiddleName = x.MiddleName,
LastName = x.LastName,
}).ToList();
Now is where I will query a another data source ( in memory for this question)
var personContactRoles = new List<FindPersonContactViewModel>()
{ new FindPersonContactViewModel { PersonID = 3197908, FirstName = "John", MiddleName= "", LastName="Smith", ContactType="Farmer", ContactRoleTypeId = 1, ExistInContactManager = true, ActionType = true, IsInContactManager = true },
new FindPersonContactViewModel { PersonID = 3197908, FirstName = "John", MiddleName= "", LastName="Smith", ContactType="Plumber", ContactRoleTypeId = 2, ExistInContactManager = true, ActionType = true, IsInContactManager = true },
new FindPersonContactViewModel { PersonID = 3197908, FirstName = "John", MiddleName= "", LastName="Smith", ContactType="Landscaper", ContactRoleTypeId = 3, ExistInContactManager = true, ActionType = true, IsInContactManager = true },
new FindPersonContactViewModel { PersonID = 2, FirstName = "Jon", MiddleName= "", LastName="Smither" },
new FindPersonContactViewModel { PersonID = 4, FirstName = "Jo", MiddleName= "", LastName="Smith" },
new FindPersonContactViewModel { PersonID = 5, FirstName = "Jody", MiddleName= "", LastName="Smith" },
new FindPersonContactViewModel { PersonID = 6, FirstName = "Johnn", MiddleName= "", LastName="Smith" },
new FindPersonContactViewModel { PersonID = 7, FirstName = "Jake", MiddleName= "", LastName="Smith" },
new FindPersonContactViewModel { PersonID = 8, FirstName = "Jock", MiddleName= "", LastName="Smith" },
};
Things to notice 1. PersonID of 3197908 is in here 3 times BECAUSE they have a different ContactRoleTypeId and ContactType
So thus my GOAL is to end up joining the data to have result collection like this
PersonID | FirstName | LastName | ContactRoleTypeId | ContactType
3197908 John Smith 1 Farmer
3197908 John Smith 2 Plumber
3197908 John Smith 3 Landscaper
4444 Jody Smith
55555 Jon Smither
I was trying to join
var ids = from azed in azedIdentity
join personRole in personContactRoles on azed.PersonID equals personRole.PersonID
select personRole;
I am thinking I need to have 2 nexted foreach loops ?????
Collection Poco model used for both sources is this:
public class FindPersonContactViewModel
{
public int PersonID { get; set; }
public string AZEDID { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public int? GenderTypeId { get; set; }
public string DOB { get; set; }
public int ContactRoleTypeId { get; set; }
public string ContactType { get; set; }
public int PersonTypeId { get; set; }
public string PreferredPhone { get; set; }
public string PreferredEmail { get; set; }
public string PhysicalAddress { get; set; }
public bool ExistInContactManager { get; set; }
public bool ActionType { get; set; }
public bool IsInContactManager { get; set; }
}
var result = from azed in azedIdentity join personRole in personContactRoles on azed.PersonID equals personRole.PersonID
into r1 from p in r1.DefaultIfEmpty() select
new FindPersonContactViewModel{PersonID = azed.PersonID, FirstName = azed.FirstName, LastName = azed.LastName,
ContactRoleTypeId = p == null ? 0 : p.ContactRoleTypeId, ContactType = p == null ? "" : p.ContactType};
You can achieve expected results with following:
var results = personContactRoles.Join(
azedIdentity,
x => x.FirstName + x.LastName,
y => y.FirstName + y.LastName,
(x, y) => new FindPersonContactViewModel()
{
PersonID = y.PersonID,
FirstName = y.FirstName,
LastName = y.LastName,
ContactRoleTypeId = x.ContactRoleTypeId,
ContactType = x.ContactType
});
however you will get 0 at ContactRoleTypeId since your POCO FindPersonContactViewModel.ContactRoleTypeId is not nullable integer

TypeError: this.model.currentViewData is undefined (In Implimentation of Hierarchical Grid --> Child Grid)

I am implementing a Hierarchy Grid in ASP.Net MVC using syncfusion Grid Control.
I am fetching the data from server side with an ajax call on the expansion of child grid. When i try to expand child grid, the ajax call fetches the data in JSON format and a JavaScript error (TypeError: this.model.currentViewData is undefined) occurs and data in the child grid doesn't load into child grid.
Details of Question and running source code example are also available here.
Classes
public class Data
{
public int OrderID { get; set; }
public int EmployeeID { get; set; }
public string ShipCountry { get; set; }
public List<ChildData> Employee { get; set; }
}
public class ChildData
{
public int EmployeeID { get; set; }
public string FirstNAme { get; set; }
public string LastNAme { get; set; }
}
Controller
public class GridController : Controller
{
//
// GET: /Grid/
List<Data> obj = new List<Data>();
public ActionResult GridFeatures()
{
var DataSource = GetData();
ViewBag.datasource = DataSource.ToList();
return View();
}
public JsonResult GetChildData(int _empID)
{
var ChildDaqtaSource = ChildData(_empID);
return Json(ChildDaqtaSource, JsonRequestBehavior.AllowGet);
}
public static List<Data> GetData()
{
List<Data> obj = new List<Data>();
//obj.Add(new Data() { OrderID = 1000, EmployeeID = 1, ShipCountry = "india", Employee = new List<ChildData>() { new ChildData() { EmployeeID = 1, FirstNAme = "Janet", LastNAme = "David" } } });
//obj.Add(new Data() { OrderID = 1001, EmployeeID = 2, ShipCountry = "France", Employee = new List<ChildData>() { new ChildData() { EmployeeID = 2, FirstNAme = "Nancy", LastNAme = "John" } } });
//obj.Add(new Data() { OrderID = 1002, EmployeeID = 3, ShipCountry = "US", Employee = new List<ChildData>() { new ChildData() { EmployeeID = 3, FirstNAme = "David", LastNAme = "Staven" } } });
//obj.Add(new Data() { OrderID = 1003, EmployeeID = 4, ShipCountry = "US", Employee = new List<ChildData>() { new ChildData() { EmployeeID = 4, FirstNAme = "Janet", LastNAme = "David" } } });
obj.Add(new Data() { OrderID = 1000, EmployeeID = 1, ShipCountry = "india" });
obj.Add(new Data() { OrderID = 1001, EmployeeID = 2, ShipCountry = "France" });
obj.Add(new Data() { OrderID = 1002, EmployeeID = 3, ShipCountry = "US" });
obj.Add(new Data() { OrderID = 1003, EmployeeID = 4, ShipCountry = "US" });
return obj;
}
public static List<ChildData> ChildData(int _EmpID)
{
List<ChildData> _childData = new List<ChildData>();
_childData.Add(new ChildData { EmployeeID = 1, FirstNAme = "John", LastNAme = "Freeman" });
_childData.Add(new ChildData { EmployeeID = 1, FirstNAme = "steve", LastNAme = "Alexander" });
_childData.Add(new ChildData { EmployeeID = 1, FirstNAme = "Ali", LastNAme = "Naeem" });
_childData.Add(new ChildData { EmployeeID = 1, FirstNAme = "Alex", LastNAme = "Wonder" });
_childData.Add(new ChildData { EmployeeID = 1, FirstNAme = "Bill", LastNAme = "Gates" });
_childData.Add(new ChildData { EmployeeID = 1, FirstNAme = "Alan", LastNAme = "Turing" });
_childData.Add(new ChildData { EmployeeID = 2, FirstNAme = "Mark", LastNAme = "Anthoney" });
_childData.Add(new ChildData { EmployeeID = 2, FirstNAme = "Carl", LastNAme = "Shoemaker" });
_childData.Add(new ChildData { EmployeeID = 3, FirstNAme = "Carlos", LastNAme = "Anthony" });
return _childData.Where(x => x.EmployeeID == _EmpID).ToList();
}
}
Razor View (GridFeatures.cshtml)
#model List<RemoteSaveAdaptorSample.Controllers.Data>
<h2>Requisitions</h2>
#(Html.EJ().Grid<RemoteSaveAdaptorSample.Controllers.Data>("EmployeeGrid")
.Datasource((List<RemoteSaveAdaptorSample.Controllers.Data>)ViewBag.DataSource)
//.Datasource(Model)
.AllowSorting(true)
.AllowResizing(true)
.AllowPaging(true)
.AllowGrouping(true)
.AllowTextWrap(true)
.AllowScrolling(true)
.AllowFiltering()
.EnableRowHover(true)
.Columns(col =>
{
col.Field(x => x.EmployeeID).HeaderText("EmployeeID").Width(30).IsPrimaryKey(true).AllowResizing(false).Add();
col.Field(x => x.OrderID).HeaderText("OrderID").Width(60).AllowFiltering(true).Add();
col.Field(x => x.ShipCountry).HeaderText("Country").Width(100).Add();
})
.ChildGrid
//<RemoteSaveAdaptorSample.Controllers.ChildData>
(_childGrid =>
{
_childGrid
.QueryString("EmployeeID")
.AllowPaging()
.Columns(_childCol =>
{
_childCol.Field("EmployeeID").HeaderText("EmployeeID").Add();
_childCol.Field("FirstNAme").HeaderText("First Name").Add();
})
.ClientSideEvents(x => x.Load("loadEvent"))
;
})
)
<script type="text/javascript">
function loadEvent(args) {
var data = this.model.parentDetails.parentKeyFieldValue;
this.model.dataSource = ej.DataManager({
url: "/grid/GetChildData?_empID=" + data + ""
, adaptor: "UrlAdaptor"
});
}
</script>
Any help is appriciated
Thanx
I have checked the query and found that you have returned the result alone from server side instead of passing it as result and count pair. When using UrlAdaptor it is must to return the data as result and count pair. So that it will bind the data to the grid.
Refer the code example
public JsonResult GetChildData(int _empID)
{
var ChildDaqtaSource = ChildData(_empID);
var count = ChildDaqtaSource.Count;
return Json(new { result = ChildDaqtaSource, count = count });
}
Refer the documentation link of UrlAdaptor
Link: https://help.syncfusion.com/aspnetmvc/grid/data-adaptors#url-adaptor

An unhandled exception of type 'System.ArgumentNullException' occurred in System.Xml.Linq.dll Additional information: Value cannot be null

I have created a class Employee which is given below
class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public int Salary { get; set; }
public static Employee[] GetAllEmployee()
{
Employee[] Emp = new Employee[5];
Emp[0] = new Employee { Id = 101, Name = "Mery", Gender = "Female", Salary = 10000 };
Emp[1] = new Employee { Id = 102, Name = "Lucy", Gender = "Female", Salary = 12000 };
Emp[2] = new Employee { Id = 103, Name = "Jeny", Gender = "Female", Salary = 15000 };
Emp[3] = new Employee { Id = 104, Name = "Lilly", Gender = "Female",Salary = 10000 };
Emp[4] = new Employee { Id = 105, Name = "Sony", Gender = "Female", Salary = 17000 };
return Emp;
}
Now I want to retrieve name of the employees whose salary is above 10000.
So I use this code but it gives error what correction should be needed?
IEnumerable<string> Names = from Emps in XDocument.Load(#"path\Data.xml")
.Descendants("Employee")
where (int)Emps.Element("Salary") > 10000
select Emps.Element("Name").Value;
foreach(string name in Names)
{
Console.WriteLine(name);
Console.ReadLine();
}
Code below works. An xml document cannot have an array at the root level.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
Company company = new Company();
XmlSerializer serializer = new XmlSerializer(typeof(Company));
StreamWriter writer = new StreamWriter(FILENAME);
serializer.Serialize(writer, company);
writer.Flush();
writer.Close();
writer.Dispose();
IEnumerable<string> Names = from Emps in XDocument.Load(FILENAME)
.Descendants("Employee")
where (int)Emps.Element("Salary") > 10000
select Emps.Element("Name").Value;
foreach (string name in Names)
{
Console.WriteLine(name);
}
Console.ReadLine();
}
}
public class Company
{
[XmlElement("Employee")]
public Employee[] employees = Employee.GetAllEmployee();
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public int Salary { get; set; }
public static Employee[] GetAllEmployee()
{
Employee[] Emp = new Employee[5];
Emp[0] = new Employee { Id = 101, Name = "Mery", Gender = "Female", Salary = 10000 };
Emp[1] = new Employee { Id = 102, Name = "Lucy", Gender = "Female", Salary = 12000 };
Emp[2] = new Employee { Id = 103, Name = "Jeny", Gender = "Female", Salary = 15000 };
Emp[3] = new Employee { Id = 104, Name = "Lilly", Gender = "Female", Salary = 10000 };
Emp[4] = new Employee { Id = 105, Name = "Sony", Gender = "Female", Salary = 17000 };
return Emp;
}
}
}

How to Use Effeciently Where Clause or Select in LINQ Parallel in Large Dataset

I'm having approx 250,000 records as marked as Boss, each Boss has 2 to 10 Staff. Daily I need to get the details of the Staff. Approx there are 1,000,000 staff. I'm using Linq to get the Unique list of Staff who are worked in daily basis. Consider the following C# LINQ and Models
void Main()
{
List<Boss> BossList = new List<Boss>()
{
new Boss()
{
EmpID = 101,
Name = "Harry",
Department = "Development",
Gender = "Male",
Employees = new List<Person>()
{
new Person() {EmpID = 102, Name = "Peter", Department = "Development",Gender = "Male"},
new Person() {EmpID = 103, Name = "Emma Watson", Department = "Development",Gender = "Female"},
}
},
new Boss()
{
EmpID = 104,
Name = "Raj",
Department = "Development",
Gender = "Male",
Employees = new List<Person>()
{
new Person() {EmpID = 105, Name = "Kaliya", Department = "Development",Gender = "Male"},
new Person() {EmpID = 103, Name = "Emma Watson", Department = "Development",Gender = "Female"},
}
},
..... ~ 250,000 Records ......
};
List<Person> staffList = BossList
.SelectMany(x =>
new[] { new Person { Name = x.Name, Department = x.Department, Gender = x.Gender, EmpID = x.EmpID } }
.Concat(x.Employees))
.GroupBy(x => x.EmpID) //Group by employee ID
.Select(g => g.First()) //And select a single instance for each unique employee
.ToList();
}
public class Person
{
public int EmpID { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public string Gender { get; set; }
}
public class Boss
{
public int EmpID { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public string Gender { get; set; }
public List<Person> Employees { get; set; }
}
In the above LINQ I'm getting the List of Distinct Employees or Staff, the list contains more than 1,000,000 records. From the Obtained List I need to search "Raj"
staffList.Where(m => m.Name.ToLowerInvariant().Contains("Raj".ToLowerInvariant()));
For this operation, it took more than 3 to 5 minutes to get the result.
How could I make it more efficient. Kindly assist me...
If you change Boss to inherit from Person ( public class Boss : Person ) not only do you not need to duplicate your properties in Person and Boss, you don't have to create all new Person instances for each Boss, because a Boss is already a Person:
IEnumerable<Person> staff = BossList
.Concat(BossList
.SelectMany(x => x.Employees)
)
.DistinctBy(p => p.EmpId)
.ToList()
Where DistinctByis defined as
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
var seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
Also, in your comparison, you're converting every Name to lowercase and doing the comparison - that's a lot of string creation that you don't need. Instead, try something like
staffList.Where(m => m.Name.Equals("Raj", StringComparison.InvariantCultureIgnoreCase));
Also, be aware that your use of Contains would also match names like Rajamussenand mirajii - possibly not what you were expecting.
Would it work for you to change staffList to a Dictionary? A better search algorithm as those from Dictionary and SortedList would get you the most improvement.
I've tested the code below and it runs in just a few seconds.
private static void Main()
{
List<Boss> BossList = new List<Boss>();
var b1 = new Boss()
{
EmpID = 101,
Name = "Harry",
Department = "Development",
Gender = "Male",
Employees = new List<Person>()
{
new Person() {EmpID = 102, Name = "Peter", Department = "Development", Gender = "Male"},
new Person() {EmpID = 103, Name = "Emma Watson", Department = "Development", Gender = "Female"},
}
};
var b2 = new Boss()
{
EmpID = 104,
Name = "Raj",
Department = "Development",
Gender = "Male",
Employees = new List<Person>()
{
new Person() {EmpID = 105, Name = "Kaliya", Department = "Development", Gender = "Male"},
new Person() {EmpID = 103, Name = "Emma Watson", Department = "Development", Gender = "Female"},
}
};
Random r = new Random();
var genders = new [] {"Male", "Female"};
for (int i = 0; i < 1500000; i++)
{
b1.Employees.Add(new Person { Name = "Name" + i, Department = "Department" + i, Gender = genders[r.Next(0, 1)], EmpID = 200 + i });
b2.Employees.Add(new Person { Name = "Nam" + i, Department = "Department" + i, Gender = genders[r.Next(0, 1)], EmpID = 1000201 + i });
}
BossList.Add(b1);
BossList.Add(b2);
Stopwatch sw = new Stopwatch();
sw.Start();
var emps = BossList
.SelectMany(x =>
new[] {new Person {Name = x.Name, Department = x.Department, Gender = x.Gender, EmpID = x.EmpID}}
.Concat(x.Employees))
.GroupBy(x => x.EmpID) //Group by employee ID
.Select(g => g.First());
var staffList = emps.ToList();
var staffDict = emps.ToDictionary(p => p.Name.ToLowerInvariant() + p.EmpID);
var staffSortedList = new SortedList<string, Person>(staffDict);
Console.WriteLine("Time to load staffList = " + sw.ElapsedMilliseconds + "ms");
var rajKeyText = "Raj".ToLowerInvariant();
sw.Reset();
sw.Start();
var rajs1 = staffList.AsParallel().Where(p => p.Name.ToLowerInvariant().Contains(rajKeyText)).ToList();
Console.WriteLine("Time to find Raj = " + sw.ElapsedMilliseconds + "ms");
sw.Reset();
sw.Start();
var rajs2 = staffDict.AsParallel().Where(kvp => kvp.Key.Contains(rajKeyText)).ToList();
Console.WriteLine("Time to find Raj = " + sw.ElapsedMilliseconds + "ms");
sw.Reset();
sw.Start();
var rajs3 = staffSortedList.AsParallel().Where(kvp => kvp.Key.Contains(rajKeyText)).ToList();
Console.WriteLine("Time to find Raj = " + sw.ElapsedMilliseconds + "ms");
Console.ReadLine();
}
public class Person
{
public int EmpID { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public string Gender { get; set; }
}
public class Boss
{
public int EmpID { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public string Gender { get; set; }
public List<Person> Employees { get; set; }
}
}
Output1:
Output2 (using .AsParallel() on searches):
In other words, if you can't use some faster data structure, up can speed your search up just by changing form
staffList.Where(m => m.Name.ToLowerInvariant().Contains("Raj".ToLowerInvariant()));
to
staffList.AsParallel().Where(m => m.Name.ToLowerInvariant().Contains("Raj".ToLowerInvariant()));

How to Display the Members of a Class

I'm trying to create a wrapper for selecting multiple items from a single array. I get the result at the end of the code below. Not sure what I'm doing wrong.
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 is what i get repeated when I run the program.
Console.WriteLine uses the ToString method of the object class. By default, that displays the name of the class.
This method is overridden by classes derived from object to display whatever they want. You have not overridden it, so you get the default.
You can reproduce your problem, without LINQ, as follows:
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"
default the ToString will be used, use:
class Names
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
It's also possible to create an extra property for the fullname
class Names
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
}
usage:
foreach (Names entry in customerfullName)
{
Console.WriteLine(entry.FullName);
}
Your Names class has not overridden the ToString method, so it is using the default implementation from object and printing out it's type name. You either need to override ToString in Names to print out the underlying strings, or you need to print out the individual string properties in your foreach loop.

Categories