I have an Entity Class called Session and it containts two attributes: LecturerOne and LectureTwo. I want to create a union of all the distinct names in LecturerOne and LecturerTwo:
I got just LecturerOne working.
public List<string> ListLecturer()
{
var lecturerNames = (from s in db.Sessions
select s.LecturerOne).Distinct();
List<string> lecturerList = lecturerNames.ToList();
return lecturerList;
}
One option:
var list = db.Sessions.SelectMany(s => new string[] { s.LecturerOne,
s.LecturerTwo })
.Distinct()
.ToList();
I don't know offhand how EF will treat that, but it's worth a try...
Alternatively, similar to Jamiec's answer but IMO simpler:
var list = db.Sessions.Select(s => s.LecturerOne)
.Union(db.Sessions.Select(s => s.LecturerTwo))
.ToList();
(Union already returns distinct results, so there's no need to do it explicitly.)
var lecturerOnes = (from s in db.Sessions
select s.LecturerOne);
var lecturerTwos = (from s in db.Sessions
select s.LecturerTwo);
List<string> lecturerList = lecturerOnes.Union(lectureTwos).ToList();
Related
I am trying to link up the RestaurantId in the RestaurantReservationEventsTbl with the RestaurantID in the RestaurantTbl to display reservations that are only made for the currently logged in restaurant.
I am receiving the following error in my code operator == cannot be applied to operands of type int and iqueryable int
Here is what I am doing in my home controller
var RestaurantIDRestaurantTbl = from r in db.Restaurants select r.RestaurantID;
//var listOfRestaurantsReservations = db.RestaurantReservationEvents.ToList();
var listOfRestaurantsReservations = db.RestaurantReservationEvents.Where(x => x.RestaurantID == RestaurantIDRestaurantTbl).ToList();
//return View(restaurants.Where(x => x.RestaurantEmailAddress == UserEmail).ToList());
//create partial view called _RestaurantReservation
return PartialView("_RestaurantReservations", listOfRestaurantsReservations);
You have to change your code to materialize the restaurantIds like this:
var RestaurantIDRestaurantTbl = (from r in db.Restaurants
select r.RestaurantID).ToList();
Then you may change the code as below for the comparison to work:
var listOfRestaurantsReservations = db.RestaurantReservationEvents.Where(x => RestaurantIDRestaurantTbl.Contains(x.RestaurantID)).ToList();
Anyway this is not the best solution. I will write another example for you, just try this example if it is working or not and let me know for the result.
I would considering changing the code as below to be much more efficient:
var listOfRestaurantsReservations = (from r in db.Restaurants
join e in db.RestaurantReservationEvents
on r.RestaurantID equals e.RestaurantID
//where r.RestaurantID == something //if where condition needed
select e).ToList();
If your tables are not connected with foreignkeys please consider to read this documentation here to make a better structure of the tables since they are related to each-other.
If your tables are related as in documentation article you might have something like that:
var RestaurantIDRestaurantTbl = db.Restaurants.SingleOrDefault(x => x.RestaurantID == something);
if(RestaurantIDRestaurantTbl != null)
{
var listOfRestaurantsReservations = RestaurantIDRestaurantTbl.RestaurantReservationEvents.ToList();
}
{
// This will give you a list of IDs
var RestaurantIDRestaurantTbl = db.Restaurants
.Select(p => p.RestaurantID)
.ToList();
// Using .Any() is a better choice instead of .Contains()
// .Contains is used to check if a list contains an item while .Any will look for an item in a list with a specific ID
var listOfRestaurantsReservations = db.RestaurantReservationEvents
.Where(p => RestaurantIDRestaurantTbl.Any(r => r.pRestaurantID == p))
.ToList();
}
I am new in linq and I want to use it in a list without use a foreach. How can I return a list from a list of objects List<House> where house ha swimming pool.
Class Houses
{
Int Id,
bool HasSwimmingPool
...
}
All you need is Where method, which filters collection based of given predicate:
var results = source.Where(x => x.HasSwimmingPool).ToList();
Additional ToList() call makes the results List<House> instead of IEnumerable<House>.
You can achieve the same using syntax-based query:
var results = (from h in source
where h.HasSwimmingPool
select h).ToList();
That is simple:
var yourCollection = new List<Houses>();
var housesThatHasASwimmingPool = yourCollection.Where(s => s.HasSwimmingPool);
try this:
var swimmngHomes = listOfHouses.
Where( h => h.HasSwimmingPool == true);
List<Houses> housesWithPools = oldHouses.Where(x => x.HasSwimmingPool== true);
I need to compare and get the matching values from a string list with LINQ. Have a look at my code.
Code
Split = Id.Split(',');
List<string> uids = new List<string>(Split);
var model = (from xx in Db.ItemWeedLogs
where xx.ItemNo == uids
// I need to pass a string list to extract the matching record.
select xx).ToList();
Try this :
var model = (from xx in Db.ItemWeedLogs
where uids.Contains(xx.ItemNo)
select xx).ToList();
Try:
where uid.contains(xx.ItemNo)
I think this is much more faster and clear.
var model = Db.ItemWeedLogs
.Join(Id.Split(','), di => di.ItemNo, si => si, (d, s) => new {d})
.ToList();
I have 2 lists. 1 is a collection of products. And the other is a collection of products in a shop.
I need to be able to return all shopProducts if the names match any Names in the products.
I have this but it doesn't seem to work. Any ideas?
var products = shopProducts.Where(p => p.Name.Any(listOfProducts.
Select(l => l.Name).ToList())).ToList();
I need to say give me all the shopproducts where name exists in the other list.
var products = shopProducts.Where(p => listOfProducts.Any(l => p.Name == l.Name))
.ToList();
For LINQ-to-Objects, if listOfProducts contains many items then you might get better performance if you create a HashSet<T> containing all the required names and then use that in your query. HashSet<T> has O(1) lookup performance compared to O(n) for an arbitrary IEnumerable<T>.
var names = new HashSet<string>(listOfProducts.Select(p => p.Name));
var products = shopProducts.Where(p => names.Contains(p.Name))
.ToList();
For LINQ-to-SQL, I would expect (hope?) that the provider could optimise the generated SQL automatically without needing any manual tweaking of the query.
You could use a join, for example:
var q = from sp in shopProducts
join p in listOfProducts on sp.Name equals p.Name
select sp;
A fuller guide on join is here.
You could create an IEqualityComparer<T> that says products with equal names are equal.
class ProductNameEqulity : IEqualityComparer<Product>
{
public bool Equals(Product p1, Product p2)
{
return p1.Name == p2.Name
}
public int GetHashCode(Product product)
{
return product.Name.GetHashCode();
}
}
Then you can use this in the Intersect extension method.
var products = shopProducts.Intersect(listOfProducts, new ProductNameEquality());
Try this please
var products = shopProducts.Where(m=> listOfProducts.Select(l=>l.Name).ToList().Contains(m=>m.Name));
var products = shopProducts
.Where(shopProduct =>
listOfProducts.Any(p => shopProduct.Name == p.Name))
.ToList();
I'm passing from the controller an array generated by the next code:
public ActionResult GetClasses(bool ajax, string kingdom)
{
int _kingdom = _taxon.getKingdom(kingdom);
var query = (from c in vwAnimalsTaxon.All()
orderby c.ClaName
select new { taxRecID = c.ClaRecID, taxName = c.ClaName }).Distinct();
return Json(query, JsonRequestBehavior.AllowGet);
}
The query List should be ordered, but it doesn't work, I get the names of the classes ordered wrong in the array, because I've seen it debugging that the names are not ordered.The view is just a dropdownbox loaded automatically, so I'm almost sure the problem is with the action. Do you see anything wrong?Am I missing something?
I think gmcalab is almost there. The reason it's not working is that Distinct blows away the ordering. So you need Distinct THEN OrderBy. But this means you have to sort by the new attribute name:
var query = (from c in vwAnimalsTaxon.All()
select new { taxRecID = c.ClaRecID, taxName = c.ClaName }
).Distinct().OrderBy(t => t.taxName);
Give this a try:
var query = (from c in vwAnimalsTaxon.All()
select new { taxRecID = c.ClaRecID, taxName = c.ClaName }
).Distinct().OrdeyBy(c => c.ClaName);
In LINQ the Distinct method makes no guarantees about the order of results. In many cases the Distinct causes the OrderBy method to get optimized away. So it's necessary to do the OrderBy last, after the Distinct.
var query = (from c in vwAnimalsTaxon.All()
select new { taxRecID = c.ClaRecID, taxName = c.ClaName })
.Distinct()
.OrderBy(c => c.ClaName);
The select will also blow away the sorting. So either Distinct or Select needs orderby after.