I've always ignored the need for LINQ by iterating over objects but recently decided its time to leave behind the old school methods and get with the times.
I'm wondering if someone can help me simplify the below code by firstly, using Lambda instead of old school Linq and secondly, the below code will always return only 1 value.. How can I cast directly to the correct type (Player) in this case without having to iterate again?
MyEntities entity = new MyEntities();
Guid selectedPlayerID = Guid.Parse(lbPlayers.SelectedItem.Value);
var player = from n in entity.Players
where n.ID == selectedPlayerID
select n;
foreach (var item in player)
{
tbPlayerSurname.Text = item.Name;
tbPlayerName.Text = item.Surname;
}
If entity.Players contain Player objects you can simply specify
IEnumerable<Player> players = entity.Players
.Where(p => p.ID == selectedPlayerID);
I was having trouble understanding your post so my initial answer was to actually select only one (and reading comments i see that is what you wanted) which you could do like this:
Player player = entity.Players.Single(p => p.ID == selectedPlayerID);
This throws and error if there are not excatly one, you could use SingleOrDefault and check for null, or even FirstOrNull, in which case you risk swallowing a potential error if there were more than one and that is supposed to get caught
var blahs = entity.Players.Where(x => x.ID == selectedPlayerID)
.Select(x => new blah() { Name = x.Name, Text = x.Surname);
This gives you an IEnumerable<Blah>.
Does it make sense?
You can use:
entity.Players.Single(n=>n.ID==selectedPlayerId);
if you think it might not exist use SingleOrDefault (and check the return value being different from default, null in case of classes).
if you care only about the first one use First or FirstOrDefault instead.
Try this code below if **entity.Players is of type List<Player>
List<Player> selectedPlayers = (from n in entity.Players
where n.ID == selectedPlayerID select n).ToList();
And if entity.Players is not of type List<Player>
List<Player> selectedPlayers = (from n in entity.Players
where n.ID == selectedPlayerID
select new Player() { Name = n.Name, Surname = n.Surname } );
Related
How can I make the performance better of the code below?
I'm loading the carItems from an external webservice in a list.
carItem is checked whether it exists in EF.
If carItem is new, then it's mapped to carsCol and added to the database. What are some easy ways to improve the performance of this using code?
carItems = carItems.Where(x => x.Name == "Tesla");
// Filter existing cars
List<Car> carsCol = new List<Car>();
foreach (var item in carItems)
{
if (GetById(item.Id) == null)
{
carsCol.Add(item);
}
}
Entities.AddRange(carsCol);
Depending on the situation, you can try to find out which ids already exist in the database by making a single query before the foreach.
var newCarItemIds = carItems.Select(x => x.Id);
var alreadyExistentCarItemIds = Entities.CarItems.Where(x => newCarItemIds.Contains(x.Id)).Select(x=>x.Id);
foreach(var item in carItems)
{
if(!alreadyExistentCarItemIds.Contains(x))
{
carsCol.Add(item);
}
}
You can use Distinct Linq functions: example
You must to implement IEquatable interface
I would propose this. You can do a left outter join with the cars that you get from your API and the existing one. Than you get the new cars that will be added.
var newCars = (from c in carItems
join e in Entities.CarItems on c.Id equals e.Id into g
from x in g.DefaultIfEmpty()
select new { c, IsNew = x == null }).Where(x = x.IsNew).ToList()
With that you do only one access to the database. Also when working with IEnumerable is always good to convert it to either a list or array, that way each time that you iterates through that object you don't run a query in your database.
I have an object called Ticket with that contains a list of objects called TicketActions. The Ticket object has a field called Date_Closed and the Actions object has a field called Action_Date:
Ticket
Date_Closed
TicketActions
-Action_Date
What I'm trying to do is order a List of tickets (List) based on the latest date of each Action in ascending order where the Ticket does not have a value for Date_Closed. The goal is to load this list into a listview and show tickets in a way that displays tickets in order on the page, placing the ones that have gone the longest without an action at the top. Does that make sense?
Here is what I ended up with so far that isn't working:
protected List<FullTicket> BuildTickets(int ticketsToShow)
{
using (var db = new SupportLogDBDataContext())
{
var result =
(from ticket in db.Support_Tickets
join status in db.Ticket_Statuses on ticket.Status_ID equals status.ID
select new FullTicket
{
TicketID = ticket.ID,
DateOpened = (DateTime)ticket.Date_Opened,
DateClosed = (DateTime)ticket.Date_Closed,
Subject = ticket.Subject,
Status = new KeyPair { Key = status.Status, Value = status.ID },
CreatedBy = new GuidPair { Key = ticket.Reported_By, Value = (Guid)ticket.AD_GUID },
TicketActions =
(from a in db.Ticket_Actions
where a.Ticket_ID == ticket.ID
select a).ToList()
}).Take(ticketsToShow).ToList();
result.OrderBy(i => i.TicketActions.Where(i.DateClosed == null).Max()); //error on this line (invalid arguments)
return result;
}
}
People reply quick here!
Try this:
var result = (from ticket in tickets
where !ticket.DateClosed.HasValue
select ticket).OrderByDescending(t => (from a in t.TicketActions
select a.ActionDate).Max());
From here you can take as many as you need.
David B's analysis is slightly off. The line...
result.OrderBy(i => i.TicketActions.Where(i.DateClosed == null).Max());
... will not compile because the argument to the Where method is not a lambda expression or delegate.
I would suggest this solution (assuming that the relevant property of the TicketAction type is ActionDate):
return result.Where(i => i.DateClosed == null)
.OrderBy(i => i.TicketActions.Max(a => a.ActionDate));
Or, in query comprehension syntax:
return from i in result
where i.DateClosed == null
orderby i.TicketActions.Max(a => a.ActionDate)
select i;
Here is some simple code.
var sorted = tickets.Where(t => t.DateClosed == null)
.OrderBy(t => t.TicketActions.Max(ta => ta.Action_Date.Ticks));
Sorry, I prefer LINQ function syntax, but if you want it in query syntax, it shouldn't be too hard to convert.
result.OrderBy(i => i.TicketActions.Where(i.DateClosed == null).Max());
This line generates an error because TicketActions.Max() is not defined.
You need to project TicketAction into something that can be Max'd. For example:
result.OrderBy(i =>
i.TicketActions
.Where(ta => i.DateClosed == null)
.Select(ta => ta.Id)
.Max()
);
Also note:
OrderBy does not modify its source. OrderBy returns an ordered IEnumerable, which you didn't assign anywhere.
OrderBy's enumerable is deferred, and you want a List result instead, so you should call ToList.
You are accessing Ticket.TicketActions outside of the query. This will cause one database round trip per ticket to load that property.
Here is a modification to your query that avoids the problems mentioned above by ordering and using navigational properties within the query.
from ticket in db.Support_Tickets
where ticket.DateClosed == null
let lastDate = ticket.TicketActions
.Select(ta => ta.ActionDate)
.OrderByDescending(date => date)
.FirstOrDefault()
let ticketStatus = ticket.TicketStatus
order by lastDate
select new FullTicket
{
...
}
I currently a list of a Supplier class, within that supplier class is a list of orders.
Each order has a userID and an empty string variable for username.
I then have a list of users which contains userID and username.
The way I am doing this now is:
foreach(supplier s in SupplierList)
{
foreach (order o in s.childorders)
{
user u = _users.First(p => p.userid == o.userid);
o.username = u.username;
}
}
I feel this might be a little inefficient and I was wondering if it is possible to compact it down into one linq query?
The logic should be
set supplierslist.childorders.username to the value in _users where supplierslist.childorders.userid == _users.userid.
Im fairly new to Linq so any advice for this would be apreciated, or also if its a bad idea and to leave it as it is / reasons why would be good too.
Thanks
What you want to do here is iterate over a collection (many collections, really, but it doesn't make a difference) and mutate its members. LINQ is not really targeted at performing mutating operations but rather at querying. You can do it with LINQ, but it's against the spirit of the tool.
If you are constructing the SupplierList yourself, it might be possible to fetch the data appropriately with LINQ so that it comes pre-populated as you want it to be.
Otherwise, I 'd leave the foreach as it is. You can make a dictionary that maps ids to users to make the inner loop faster, but that's your call and it depends on your data size.
var orderUserPairs = SupplierList
.SelectMany(s => s.ChildOrders)
.Join(_users, o => o.UserId, u => u.userId, (Order, User) => new {Order, User});
foreach (var orderUserPair in orderUserPairs)
orderUserPair.Order.username = orderUserPair.User.username;
Though having both username and userId as part of order looks suspicious.
First a question...
It looks like you are operating on every order. Why do you need to cycle through the supplierlist first since you don't seem to be using it inside the loop? Unless there are orders that don't belong to any supplierlist, you might be able to skip that step.
If that isn't the case, then I think you can use a join. If you aren't familiar with the syntax for joins in linq, this is one (simplified) way to approach it:
var x = from S in SupplierList
join C in childorders on C.supplierlistID equals S.ID
where [whatever you need here if anything]
select new { field1, field2};
foreach var y in x
{
}
Note I assumed a foreign key in childorders to supplierlist. If that isn't the case you will have to modify accordingly.
Hope that helps.
You need to use SelectMany or join depending on weather you are using linq-to-sql or linq with local collections. If you are using local collections the better way is to use join, else use SelectMany.
Like this...join:
var selection = (from s in SupplierList
join o in s.childholders on s.userid equals o.userid
select new { username = o.username);
or, in case of linq-to-sql:
var selection = (from s in SupplierList
from o in s.childholders
select { username = o.username);
You can then use the anonymous type you projected the way you want.
I agree with Jon, but you could say:
var orders = (from s in supplier
from o in s.childorders
select new
{
Order = o,
User = _users.First(p => p.userid == o.userid)
}).ToList();
foreach(var order in orders) {
order.Order.username = order.User.username;
}
Untested of course :)
If users list contains many elements, it can be really slow so I'd use a temporary dictionary:
var userById = users.GroupBy(x => x.userid)
.ToDictionary(x => x.Key, x => x.First());
foreach(var order in supplier.SelectMany(x => x.childorders))
{
order.username = userById[order.userid].username;
}
I have the following that pulls through a list of suppliers:
public List<tblSupplierPerformance> GetSupplierInfo(string memberid, string locationid, string supplieridname)
{
MyEntities suppliers = new MyEntities();
var r = (from p in suppliers.tblSupplierPerformances
where p.MemberId == memberid && p.LocationId == locationid
orderby p.TotalPurchaseQuantity
select p)
.Distinct();
if (supplieridname != "0")
r = r.Where(p => p.SupplierIDName == supplieridname);
return r.ToList();
}
However, when this runs, the orderby doesn't seem to be ordering.
I think, think, I need to implement the orderby at the "return r." stage, but I don't really know how to do this or I could be very much wrong all over the shop!
Any pointers gladly received.
I suspect it's the Distinct call which is messing up the ordering... although as you're not joining or doing anything like that, I'm not sure why you need distinct - isn't each entity naturally distinct?
Anyway, you could certainly move the ordering to the return statement:
return r.OrderBy(p => p.TotalPurchaseQuantity).ToList();
Yes, you need to implement order by in the return
return r.ToList().OrderBy(o => o.Column1);
Consider this:
var query = from r in this._db.Recipes
where r.RecipesID == recipeID
select new { r.RecipesID, r.RecipesName };
How would i get individual columns in my query object without using a for-loop?
Basicly: how do I translate DataTable.Rows[0]["ColumnName"] into Linq syntax?
It's really unclear what you are looking for, as your two samples are compatible.
As close as I can figure, what you want is:
var rows = query.ToList();
string name = rows[0].RecipesName;
string name = this._db.Recipes.Single(r => r.RecipesID == recipeID).RecipesName;
This is the way to go about it:
DataContext dc = new DataContext();
var recipe = (from r in dc.Recipes
where r.RecipesID == 1
select r).FirstOrDefault();
if (recipe != null)
{
id = recipe.RecipesID;
name = recipe.RecipesName;
}
Sorry, misunderstood your question. As others are saying, you can use ToList() to get a List back. An alternative if all you need is the first one, just use:
query.First().ColumnName
or if you want to avoid an exception on empty list:
var obj = query.FirstOrDefault();
if (obj != null)
obj.ColumnName;
Original Answer (so the comment makes sense):
Use Linq to Datasets. Basically would be something like:
var query = from r in yourTable.AsEnumerable()
select r.Field<string>("ColumnName");