How to convert LINQ query result to list and return generic List? - linq

I used generic ORM list
example.
This is my table.
Person table
Guid
Name
LastName
and this is my struct class.
public struct PersonItem // database and class field names are the same
{
public Guid Guid{ get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
public struct PersonItems
{
public PersonItems()
{
Items = new List<PersonItem>();
}
public List<PersonItem> Items { get; set; }
}
I'm using such and no problem but I always have to write field's
public PersonItems GetPersons()
{
var query = (from p in _DbEntities.t_Crew
select p).ToList();
if (query != null)
{
foreach (var item in query)
{
_PersonItems.Items.Add(new PersonItem
{
Guid = item.Guid,
Name = item.Name,
LastName = item.LastName
});
}
}
return _PersonItems;
}
public PersonItems GetPersons()
{
PersonItems personItems = new PersonItems();
var query = from p in _DbEntities.t_Person
select p; >> this here query I need to convert linq query result to list
personItems = query.ToList();
return personItems ;
}
error
Cannot implicitly convert type System.Collections.Generic.List' to PersonData.PersonItems'.

Try this
public PersonItems GetPersons()
{
PersonItems personItems = new PersonItems();
var query = (from p in _DbEntities.t_Person
select new PersonItems
{
test = p.SomeName,
//Other Stuff
//...
}).ToList();
return query;
}

Comparing to the other version of your GetPersons() method, I think this line :
personItems = query.ToList();
should've been this way instead :
personItems.Items = query.ToList();
Update regarding the latest error. You can't assign list of t_Person to Item property which is of type list of PersonItem. Hence, your query need to be adjusted to return list of PersonItem :
var query = from p in _DbEntities.t_Person
select new PersonItem
{
Guid = p.Guid,
Name = p.Name,
LastName = p.LastName
};
or other option is to change definition of Item property to list of t_Person :
public List<t_Person> Items { get; set; }

Cannot implicitly convert type System.Collections.Generic.List' to PersonData.PersonItems'
Above error says that you are trying to convert generic list to PersonItems.
So at this line, query.ToList() code returns List<PersonItem> not the PersonItems
var query = from p in _DbEntities.t_Person
select p; >> this here query I need to convert linq query result to list
personItems = query.ToList();
return personItems ;
So thats the reason above line of code fails.

What about this?
Change .ctor of PersonItems:
public struct PersonItems
{
public PersonItems(List<PersonItem> items)
{
Items = items;
}
public List<PersonItem> Items { get; set; }
}
And then method GetPersons():
public PersonItems GetPersons()
{
return new PersonItems(_DbEntities.t_Person.ToList());
}

Related

how to add the number of items at the end of the linq query

i have the following LINQ
public IEnumerable<TurbineStatus> turStatus()
{
var result = (from s in _db.masterData
group s by s.current_turbine_status into g
select new TurbineStatus
{
status = g.Key,
numberOfTurbines = g.Count()
}
).ToList().OrderByDescending(s => s.status);
return result;
}
my class:
public class TurbineStatus
{
public string status { get; set; }
public int numberOfTurbines { get; set; }
public int allTurbines { get; set; }
}
i gives me the number of turbines according to the status,for example, 5turbines STOP,6 turbines RUN,10 turbines Link Down and so on,i also need to have sum of all these statuses,in my TurbinesStatus class i have a field which is int and named it allTurbines,how can i achieve it?
It's probably better for performance reasons to let the DB handle sorting and then once the result is materialized, you can extract the sum of the turbines count:
var result =
(
from s in _db.masterData
group s by s.current_turbine_status into g
select new TurbineStatus
{
status = g.Key,
numberOfTurbines = g.Count()
} into statusGroup
orderby statusGroup.status descending
select statusGroup
).ToList();
int totalTurbines = groups.Sum(statusGroup => statusGroup.numberOfTurbines);
To return both as a TurbinesStatus instance:
public class TurbinesStatus
{
public IReadOnlyList<TurbineStatus> TurbineStatuses { get; }
public int TotalCount { get; }
public TurbinesStatus(IReadOnlyList<TurbineStatus> turbineStatuses)
{
TurbineStatuses = turbineStatuses;
TotalCount = turbineStatuses.Sum(ts => ts.numberOfTurbines);
}
}
and then
public TurbinesStatus turStatus()
{
var statuses =
(
from s in _db.masterData
group s by s.current_turbine_status into g
select new TurbineStatus
{
status = g.Key,
numberOfTurbines = g.Count()
} into statusGroup
orderby statusGroup.status descending
).ToList();
return new TurbinesStatus(statuses);
}

Linq to Sql Using a function to set a value

I wanted to get from a database a IEnumerable<T> and within the 'Select' method using a function to return a string value. But I always get back the
'method cannot be translated into a store expression'
error.
I already took a look all the post on Stack Overflow about the error 'LINQ to Entities does not recognize the method .... and this method cannot be translated into a store expression"
The only way that I found to get around this error is apply the function after the query has run.
void Main()
{
int eventId = 17;
IEnumerable<OccurrenceDropDownList> model = Occurrences.Select (s => new OccurrenceDropDownList
{
OccurrenceId = s.OccurrenceId,
Name = s.Name
})
.AsEnumerable()
.Select(m => new OccurrenceDropDownList
{
OccurrenceId = m.OccurrenceId,
Name = m.Name,
Selected = setSelected(m.OccurrenceId, eventId)
}).AsEnumerable();
foreach(var item in model)
{
Console.WriteLine(item.Name + " - id : " + item.OccurrenceId + " " + item.Selected);
}
}
public class OccurrenceDropDownList
{
public int OccurrenceId { get; set; }
public string Name { get; set; }
public string Selected { get; set; }
}
static string setSelected(int occurrence, int selectedid){
if(occurrence == selectedid){
return "selected";
}
return "";
}
Is there any way to apply the function as result of the first query?
It should be simplier:
int eventId = 17;
IEnumerable<OccurrenceDropDownList> model = Occurrences
.Select(s => new OccurrenceDropDownList
{
OccurrenceId = s.OccurrenceId,
Name = s.Name,
//magic ternary if
Selected = (eventId == s.OccurrenceId) ? "selected" : String.Empty
});
That's all. I used ternary if operator that should be translated to SQL.

How can I use be generic to result of linq query?

Be first, my English is not very good. So I am sorry about that. :)
My question as the title. I have two tables on my database:
Siniflar (SinifId, SinifAdi, Kapasite, OgretmenId)
Ogretmenler (OgretmenId, Ad, Soyad, Brans)
Query:
var siniflar = (from s in db.Siniflar
join o in db.Ogretmenler
on s.OgretmenId equals o.OgretmenId
select new { s.SinifId, s.SinifAdi, s.Kapasite, o.Ad }).ToList();
I want to use the result of the query as a generic, like this:
public List<Siniflar> SiniflariListele()
{
var siniflar = (from s in db.Siniflar
join o in db.Ogretmenler
on s.OgretmenId equals o.OgretmenId
select new { s.SinifId, s.SinifAdi, s.Kapasite, o.Ad }).ToList();
return siniflar;
}
But I get an error. Because the result is anonymous types.
Error: Cannot implicitly convert type System.Collections.Generic.List<AnonymousType#1> to System.Collections.Generic.List<Entity.Siniflar>
How Can I use be generic result. What Can I do for that?
I changed question:
Class:
public class RSiniflar
{
public int SinifId { get; set; }
public string SinifAdi { get; set; }
public int Kapasite { get; set; }
public string OgretmenAdiSoyadi { get; set; }
}
Metod:
public List<RSiniflar> SiniflariListele()
{
List<RSiniflar> siniflar = (from s in db.Siniflar
join o in db.Ogretmenler
on s.OgretmenId equals o.OgretmenId
select new RSiniflar
{
SinifId = s.SinifId,
SinifAdi = s.SinifAdi,
Kapasite = s.Kapasite,
OgretmenAdiSoyadi = o.Ad + ' ' + o.Soyad
}).ToList();
return siniflar;
}
But now error to query: Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.
I think, there are a problem on my query... I get an error same when query to var type...
You can return typed list, but you can't return a list of anonymous type. So you need to create a class which will handle your results:
public class A
{
public int SinifId { get; set; }
public int SiniAdi { get; set; }
public int Kapasite { get; set; }
public int Ad { get; set; }
}
And then use it in your query, instead of anonymous objects:
public List<A> SiniflariListele()
{
var siniflar = (from s in db.Siniflar
join o in db.Ogretmenler
on s.OgretmenId equals o.OgretmenId
select new A {
SinifId = s.SinifId,
SinifAdi = s.SinifAdi,
Kapasite = s.Kapasite,
Ad = o.Ad
}).ToList();
return siniflar;
}
You could do the same with an existing class (e.g. Siniflar), but you have to be sure that this class has all necessary properties.
Rather than using new { property1, property2 }, create new Siniflar's in your select.
E.g.
select new Siniflar() {
SinifId = s.SinifId,
SinifAdi = s.SinifAdi,
Kapasite = s.Kapasite }).ToList()
Note: as lazyberezovsky mentioned, your mapping seems to be flawed, as Siniflar does not contain the property Ad.

ef cf linq populate ignored property

I'm sure this has to have been asked before, but I couldn't find a good way to search on it.
I have a class like the following
public class Vendor
{
public int VendorId { get; set; }
public string Name { get; set; }
public int ProductCount { get; set; }
}
I have a configuration class setup like
public class VendorConfiguration : EntityTypeConfiguration<Vendor>
{
public VendorConfiguration()
{
Property(p => p.Name).IsRequired().HasMaxLength(128);
Ignore(v => v.ProductCount);
}
}
Here is the query i use to grab the vendors.
public Vendor[] GetVendors()
{
using (var db = new UbidContext())
{
var query = (from vendor in db.Vendors
select vendor);
return query.ToArray();
}
}
How could I populate ProductCount with a subquery that would look similar to
ProductCount = (from vend in db.VendorProducts
where vend.VendorId == id
select vend).Count()
Is there a way I can add that to the main query, so I'm only making 1 call to the db?
Thanks,
Andrew
I would try it this way:
public Vendor[] GetVendors()
{
using (var db = new UbidContext())
{
var query = from vendor in db.Vendors
join vp in db.VendorProducts
on vendor.VendorId equals vp.VendorId
into vendorProducts
select new
{
Vendor = vendor,
ProductCount = vendorProducts.Count()
};
foreach (var item in query)
item.Vendor.ProductCount = item.ProductCount;
return query.Select(a => a.Vendor).ToArray();
}
}
Problem is that you must project into a non-entity type (anonymous in the example above) and then copy the projected ProductCount value into the projected Vendor item by item before you return it.

Sorting a List of Class with LINQ

I have a List<MyClass> and I want to sort it by DateTime CreateDate attribute of MyClass.
Is that possible with LINQ ?
Thanks
To sort the existing list:
list.Sort((x,y) => x.CreateDate.CompareTo(y.CreateDate));
It is also possible to write a Sort extension method, allowing:
list.Sort(x => x.CreateDate);
for example:
public static class ListExt {
public static void Sort<TSource, TValue>(
this List<TSource> list,
Func<TSource, TValue> selector) {
if (list == null) throw new ArgumentNullException("list");
if (selector == null) throw new ArgumentNullException("selector");
var comparer = Comparer<TValue>.Default;
list.Sort((x,y) => comparer.Compare(selector(x), selector(y)));
}
}
You can enumerate it in sorted order:
IEnumerable<MyClass> result = list.OrderBy(element => element.CreateDate);
You can also use ToList() to convert to a new list and reassign to the original variable:
list = list.OrderBy(element => element.CreateDate).ToList();
This isn't quite the same as sorting the original list because if anyone still has a reference to the old list they won't see the new ordering. If you actually want to sort the original list then you need to use the List<T>.Sort method.
Here is a sample:
using System.Collections.Generic;
using System.Linq;
namespace Demo
{
public class Test
{
public void SortTest()
{
var myList = new List<Item> { new Item { Name = "Test", Id = 1, CreateDate = DateTime.Now.AddYears(-1) }, new Item { Name = "Other", Id = 1, CreateDate = DateTime.Now.AddYears(-2) } };
var result = myList.OrderBy(x => x.CreateDate);
}
}
public class Item
{
public string Name { get; set; }
public int Id { get; set; }
public DateTime CreateDate { get; set; }
}
}
Sure the other answers with .OrderBy() work, but wouldn't you rather make your source item inherit from IComparable and just call .Sort()?
class T {
public DateTime CreatedDate { get; set; }
}
to use:
List<T> ts = new List<T>();
ts.Add(new T { CreatedDate = DateTime.Now });
ts.Add(new T { CreatedDate = DateTime.Now });
ts.Sort((x,y) => DateTime.Compare(x.CreatedDate, y.CreatedDate));

Resources