I can do var lst = from p in myEntity.tblx --- no problem
instead I want to do something like
List<myClass> lst = from p in myEntity.tblx
where myClass has all the same fields as tblx
I have tried
List<myClass> lst = new List<myClass>();
lst = (from p in myEntity.tblx).ToList();
but that did not work.
say myClass looks like this
class myClass
{
int mainID {get; set;}
string fName {get; set;}
string lName {get; set;}
}
how can I populate
List<myClass> lst from myEntity.tblx
using Linq?
Did you try like below:
List<myClass> lst = (from p in myEntity.tblx
select new myClass()
{
mainID = p.mainID,
fName = p.fname,
lName = p.lName
}).ToList();
Hope this helps!
You are missing projection part
Use
lst = (from p in myEntity.tblx select new myClass()){ mainID = p.mainID, fName = p.fname, lName = p.lName}.ToList();
or
lst = myEntity.tblx.select( p => new myClass() { mainID = p.mainID, fName = p.fname, lName = p.lName}).ToList();
Related
I have the following business objects:
public class ItemCategoryBO
{
public string ItemCategory { get; set; }
public string Title { get; set; }
}
public class ItemBO
{
public int ItemId { get; set; }
public string Title { get; set; }
public string ItemCategory { get; set; }
}
List<ItemCategoryBO> categoryList = new List<ItemCategoryBO>();
ItemCategoryBO itemCategory = new ItemCategoryBO();
itemCategory.ItemCategoryCd = "CARS";
itemCategory.Title = "Cars";
ItemCategoryBO itemCategory2 = new ItemCategoryBO();
itemCategory.ItemCategoryCd = "PLANES";
itemCategory.Title = "Planes";
categoryList.Add(itemCategory);
categoryList.Add(itemCategory2);
List<ItemBO> itemList = new List<ItemBO>();
ItemBO item1 = new ItemBO();
item1.ItemId = 1;
item1.Title = "1st item";
item1.ItemCategoryCd = "OTHER";
ItemBO item2 = new ItemBO();
item2.ItemId = 2;
item2.Title = "2nd Item";
item2.ItemCategoryCd = "CARS";
ItemBO item3 = new ItemBO();
item3.ItemId = 3;
item3.Title = "3rd Item";
item3.ItemCategoryCd = "PLANES";
itemList.Add(item1);
itemList.Add(item2);
itemList.Add(item3);
If I have a list of a few categories, how could I find a list of items that contain a category in the list of categories? (In my example, I want to get back items 2 and 3)
If you have a situation like:
List<ItemBO> items;
List<ItemCategoryBO> categories;
and you wish to get all the items that have a category that is in your list of categories, you can use this:
IEnumerable<ItemBO> result = items.Where(item =>
categories.Any(category => category.ItemCategory.equals(item.ItemCategory)));
The Any() operator enumerates the source sequence and returns true as soon as an item satisfies the test given by the predicate. In this case, it returns true if the categories list contains an ItemCategoryBO where its ItemCategory string is the same as the item's ItemCategory string.
More information about it on MSDN
Try using some linq
List<ItemBO> itm = new List<ItemBO>;
//Fill itm with data
//get selected item from control
string selectedcategory = cboCatetories.SelectedItem;
var itms = from BO in itm where itm.ItemCategory = selectedcategory select itm;
itms now contains all items in that category
Here's something I did in Linqpad
void Main()
{
var cat1 = new ItemCategoryBO {ItemCategory="c1", Title = "c1"};
var cat2 = new ItemCategoryBO {ItemCategory="c2", Title = "c2"};
var item1 = new ItemBO { ItemId = 1, Title = "item1", ItemCategory="c1"};
var item2 = new ItemBO { ItemId = 1, Title = "item2", ItemCategory="c2"};
var item3 = new ItemBO { ItemId = 1, Title = "item3", ItemCategory="c2"};
var item4 = new ItemBO { ItemId = 1, Title = "item4", ItemCategory="c3"};
var items = new List() {item1, item2, item3, item4};
var categories = new List() {cat1, cat2};
var itemsInCategory = from item in items
join category in categories on item.ItemCategory equals category.ItemCategory into itemInCategory
from categoryItem in itemInCategory
select new {item.Title, item.ItemCategory};
itemsInCategory.Dump();
}
// Define other methods and classes here
public class ItemCategoryBO
{
public string ItemCategory { get; set; }
public string Title { get; set; }
}
public class ItemBO
{
public int ItemId { get; set; }
public string Title { get; set; }
public string ItemCategory { get; set; }
}
This returns:
Title, ItemCategory
item1 c1
item2 c2
item3 c2
Try this:
List<ItemBO> items = ...;
ItemCategoryBO category = ...;
List<ItemBO> filteredItems = items
.Where( i => i.ItemCategory.Equals(category) )
.FirstOrDefault();
Updated to address OP's updated question:
If I have a list of a few categories, how could I find a list of items that contain a category in the list of categories? (In my example, I want to get back items 2 and 3)
I think you actually should do this in two steps. First, get your distinct list of items. Then, from your items, get your list of categories. So:
// First, get the distinct list of items
List<ItemBO> items = new List<ItemBO>();
foreach ( var category in categories )
{
foreach ( var item in category.Items )
{
if ( !items.Contains(item) )
items.Add(item);
}
}
// Second, get the list of items that have the category.
List<ItemBO> filteredItems = items
.Where( i => i.ItemCategory.Equals(category) )
.FirstOrDefault();
Hope this helps:
var result = (Object to search in).Where(m => (Object to compare to).Any(r => r.Equals(m.Key)).ToList();
I have a class like
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Now I have a list of this class: List<Person> persons;
var persons = new List<Person> {
new Person { Id = 1, LastName = "Reza", FirstName="Jenabi" },
new Person { Id = 1, LastName = "Amin", FirstName="Golmahalle"},
new Person { Id = 2, LastName = "Hamed", FirstName="Naeemaei"}
};
Is there a way I can group by Id and get the list of all the full Name (Combine first and last names)?
So after grouping:
var Id = results[0].Id; // Output : 1
List<string> fullNames = results[0].FullNames; // Output : "Reza Jenabi","Amin Golmahalle"
I believe this is what you need:
var results = persons.GroupBy(x => x.Id)
.Select(x => new { Id = x.Key, FullNames = x.Select(p => $"{p.FirstName} {p.LastName}").ToList() })
.ToList();
I think bellow code can help you:
var fff = from p in persons
group $"{p.FirstName} {p.LastName}" by p.Id into g
select new { PersonId = g.Key, FullNames = g.ToList() };
yeah, you can use GroupBy and Join those items:
var grouped = persons.GroupBy(p => p.Id)
.Select(s => string.Join(", ", s.Select(a=> $"{a.FirstName} {a.LastName}")));
I want to convert DataTable with below sample Data
Employee subject1 subject2 subject3 .......
1 100 80 60......
2 90 70 70...
into
List.
Where Employee Object is as follows..
public class Employee
{
public int EmpId { get; set;}
public Dictionary<string,decimal> SubjectMarks;
}
Can anyone help me in converting this Datatable to List in c sharp or using linq.
So the dynamic subject-columns start at index 1 and end at table.Columns-Count-1. Then i would create an array of these columns first. Then you can use Select + ToDictionary + ToList:
DataColumn[] subjectColumns = table.Columns.Cast<DataColumn>().Skip(1).ToArray();
List<Employee> employee = table.AsEnumerable()
.Select(r => new Employee
{
EmpId = r.Field<int>("Employee"),
SubjectMarks = subjectColumns.Select(c => new
{
Subject = c.ColumnName,
Marks = r.Field<decimal>(c)
})
.ToDictionary(x => x.Subject, x => x.Marks)
}).ToList();
Assuming that the type of the columns are already int for the ID and decimal for the marks. Otherwise use int.Parse and decimal.Parse to convert them.
var list = new List<Employee>();
var id = table.Columns[0];
var marks = table.Columns.Cast<DataColumn>().Skip(1).ToArray();
foreach (DataRow row in table.Rows)
{
var obj = new Employee { EmpId = (int) row[id] };
var dict = new Dictionary<string,decimal>();
foreach (var mark in marks)
{
dict[mark.ColumnName] = (decimal)row[mark];
}
obj.SubjectMarks = dict;
list.Add(obj);
}
Instead of using a Dictionary, then you can you List to add subject grades
Try this:
public class Employee
{
public int EmpId { get; set;}
public List<string> SubjectMarks { get; set;}
}
var empList = (from emp in dtEmployeeList.AsEnumerable()
select new Employee()
{
EmpId = (int) emp["Employee"],
SubjectMarks = List<string>()
{
emp["subject1"].ToString(),
emp["subject2"].ToString(),
emp["subject3"].ToString()
}
}).ToList()
You can do like this:
System.Data.DataTable table = // your table
List<Employee> result =
table.AsEnumerable().Select(i => new Employee()
{
EmpId = i.Field<int>("Employee"),
SubjectMarks = { { "subject1", i.Field<decimal>("subject1") } ,
{ "subject2", i.Field<decimal>("subject2") } ,
{ "subject3", i.Field<decimal>("subject3") } }
}).ToList();
You'll need to make sure you have a reference to System.Data.DataSetExtensions. And don't forget to add the using System.Data.
I have to populate below class in Linq Query
public class Emp
{
public string name {get; set;}
public dynamic Obj { get; set; }
public Emp()
{
Obj = new ExpandoObject();
}
}
public LoadData()
{
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj.DOB = d.DOB,
Obj.BirthPlace = d.BirthPlace
}).ToList();
}
OR
public LoadData()
{
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj.DOB = new ExpandoObject { DOB = d.DOB, BirthPlace = d.BirthPlace } }).ToList();
}
it doesn't allow me to assign properties dynamically like above, Can anyone please help me how to achieve this?
Try this way:
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj = { DOB = d.DOB, BirthPlace = d.BirthPlace }
}).ToList();
It is very similar to #gowansg answer, but without new keyword. It is just setting of values of properties. If we will try to get Type of Obj we will recieve System.Dynamic.ExpandoObject. With new keyword it will be some anonymous type.
respectively, such constructions like:
emp[0].Obj.OtherProperty = 1;
will fail in case of using anonymous type.
You were close in your second example, you just need to set Obj equal to a new anonymous object instead of a new ExpandoObject:
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj = new { DOB = d.DOB, BirthPlace = d.BirthPlace }
}).ToList();
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj = { DOB = d.DOB, BirthPlace = d.BirthPlace }
}).ToList();
I have the following business objects:
public class ItemCategoryBO
{
public string ItemCategory { get; set; }
public string Title { get; set; }
}
public class ItemBO
{
public int ItemId { get; set; }
public string Title { get; set; }
public string ItemCategory { get; set; }
}
List<ItemCategoryBO> categoryList = new List<ItemCategoryBO>();
ItemCategoryBO itemCategory = new ItemCategoryBO();
itemCategory.ItemCategoryCd = "CARS";
itemCategory.Title = "Cars";
ItemCategoryBO itemCategory2 = new ItemCategoryBO();
itemCategory.ItemCategoryCd = "PLANES";
itemCategory.Title = "Planes";
categoryList.Add(itemCategory);
categoryList.Add(itemCategory2);
List<ItemBO> itemList = new List<ItemBO>();
ItemBO item1 = new ItemBO();
item1.ItemId = 1;
item1.Title = "1st item";
item1.ItemCategoryCd = "OTHER";
ItemBO item2 = new ItemBO();
item2.ItemId = 2;
item2.Title = "2nd Item";
item2.ItemCategoryCd = "CARS";
ItemBO item3 = new ItemBO();
item3.ItemId = 3;
item3.Title = "3rd Item";
item3.ItemCategoryCd = "PLANES";
itemList.Add(item1);
itemList.Add(item2);
itemList.Add(item3);
If I have a list of a few categories, how could I find a list of items that contain a category in the list of categories? (In my example, I want to get back items 2 and 3)
If you have a situation like:
List<ItemBO> items;
List<ItemCategoryBO> categories;
and you wish to get all the items that have a category that is in your list of categories, you can use this:
IEnumerable<ItemBO> result = items.Where(item =>
categories.Any(category => category.ItemCategory.equals(item.ItemCategory)));
The Any() operator enumerates the source sequence and returns true as soon as an item satisfies the test given by the predicate. In this case, it returns true if the categories list contains an ItemCategoryBO where its ItemCategory string is the same as the item's ItemCategory string.
More information about it on MSDN
Try using some linq
List<ItemBO> itm = new List<ItemBO>;
//Fill itm with data
//get selected item from control
string selectedcategory = cboCatetories.SelectedItem;
var itms = from BO in itm where itm.ItemCategory = selectedcategory select itm;
itms now contains all items in that category
Here's something I did in Linqpad
void Main()
{
var cat1 = new ItemCategoryBO {ItemCategory="c1", Title = "c1"};
var cat2 = new ItemCategoryBO {ItemCategory="c2", Title = "c2"};
var item1 = new ItemBO { ItemId = 1, Title = "item1", ItemCategory="c1"};
var item2 = new ItemBO { ItemId = 1, Title = "item2", ItemCategory="c2"};
var item3 = new ItemBO { ItemId = 1, Title = "item3", ItemCategory="c2"};
var item4 = new ItemBO { ItemId = 1, Title = "item4", ItemCategory="c3"};
var items = new List() {item1, item2, item3, item4};
var categories = new List() {cat1, cat2};
var itemsInCategory = from item in items
join category in categories on item.ItemCategory equals category.ItemCategory into itemInCategory
from categoryItem in itemInCategory
select new {item.Title, item.ItemCategory};
itemsInCategory.Dump();
}
// Define other methods and classes here
public class ItemCategoryBO
{
public string ItemCategory { get; set; }
public string Title { get; set; }
}
public class ItemBO
{
public int ItemId { get; set; }
public string Title { get; set; }
public string ItemCategory { get; set; }
}
This returns:
Title, ItemCategory
item1 c1
item2 c2
item3 c2
Try this:
List<ItemBO> items = ...;
ItemCategoryBO category = ...;
List<ItemBO> filteredItems = items
.Where( i => i.ItemCategory.Equals(category) )
.FirstOrDefault();
Updated to address OP's updated question:
If I have a list of a few categories, how could I find a list of items that contain a category in the list of categories? (In my example, I want to get back items 2 and 3)
I think you actually should do this in two steps. First, get your distinct list of items. Then, from your items, get your list of categories. So:
// First, get the distinct list of items
List<ItemBO> items = new List<ItemBO>();
foreach ( var category in categories )
{
foreach ( var item in category.Items )
{
if ( !items.Contains(item) )
items.Add(item);
}
}
// Second, get the list of items that have the category.
List<ItemBO> filteredItems = items
.Where( i => i.ItemCategory.Equals(category) )
.FirstOrDefault();
Hope this helps:
var result = (Object to search in).Where(m => (Object to compare to).Any(r => r.Equals(m.Key)).ToList();