How to Call Method in LINQ Select - c#

I have the following method:
internal void DuplicateGroup(int oldGroupId, int newGroupId) {
IEnumerable<int> res = (from p in Db.table
where p.GroupID == oldGroupId
select p.packSizeID);
foreach (int ps in res)
Db.table.Add(new entityclass { GroupID = newGroupId, packSizeID = ps });
}
The method builds a List from desired IDs then adds new rescords to the same table with newGroupIDs. The question is: is it possible to call method within select?

Not in that select no, but in some selects, yes. It depends on the data source. LINQ over EF, no, but LINQ over objects, yes.

Related

How to make count with linq ASP.NET C#

I´m trying to make this sql request
SELECT number, COUNT(number)
FROM Bet GROUP BY number ORDER BY COUNT(number) DESC;
Code
public static List<Apuesta> GetAllNumbers(ApplicationDbContext db)
{
List<Bet> bets = (from b in db.Bet select b.Number).Count();
return bets;
}
and i want to use it in one function using linq.
To get the result you are trying to achieve you can project your query to an anonymous type:
var bets =db.Bet.GroupBy(b=>b.Number)
.Select(g=>new {Number=g.Key, Count=g.Count()})
.OrderByDescending(e=>e.Number);
Or a DTO:
public class BetDTO
{
public int Number{get;set;}
public int Count{get;set;}
}
Then project your result using that custom class:
var bets =db.Bet.GroupBy(b=>b.Number)
.Select(g=>new BetDTO{Number=g.Key, Count=g.Count()})
.OrderByDescending(e=>e.Number)
.ToList();
In addition to #octavioccl. If you like SQL-like LINQ-expressions you can use that snippet:
var bets = from b in bets group b by b.Number into g orderby -g.Key select new { Number = g.Key, Count = g.Count() });

Get another class from LINQ to SQL query

I am a little weak in LINQ to SQL so will try to explain my problem.
I have a method as follows (simplified to explain it better):
public static List<ic_ProductData> GetCompleteSimilarProductsWithApplyButton(InfoChoiceAdminDataContext db)
{
var products = (from
p in db.ic_ProductDatas
join proddef in db.ic_ProductDefs on p.ProductDefId equals proddef.ProductDefId
select p
).ToList();
return products;
}
ic_ProductData and ic_ProductDefs are tables in my database
The ic_ProductData class contains a manually created property as:
public ic_ProductDef RelatedProductDef { get; set; }
I want to modify the above LINQ to SQL query so that I can populate this property.
Please note I do not want another call to the database.
Also there are a lot of properties in ic_ProductData so I want to avoid mapping each and every property
Something to the effect of the following (obviously the below is wrong):
public static List<ic_ProductData> GetCompleteSimilarProductsWithApplyButton(InfoChoiceAdminDataContext db)
{
var products = (from
p in db.ic_ProductDatas
join proddef in db.ic_ProductDefs on p.ProductDefId equals proddef.ProductDefId
//trying to change here
select new ic_ProductData
{
//do something with p here so that all the properties of new object gets filled
// avoid mapping of properties here
RelatedProductDef = proddef
}
).ToList();
return products;
}
With my limited knowledge I am stuck here.
Please help!
Thanks in advance!
You can do something like this:
var query = (from p in db.ic_ProductDatas
join proddef in db.ic_ProductDefs on p.ProductDefId equals proddef.ProductDefId
select new
{
ProductData = p,
Def = proddef
}).ToList();
List<ic_ProductData> products = new List<ic_ProductData>();
foreach( var product in query)
{
product.ProductData.RelatedProductDef = product.Def;
products.Add(product);
}
Basicly, you first need to do the one query to the database, this returns an anonymous type containing both your product and its Def.
Finally, you loop (in memory, no db-calls!) over these, creating your final objects with their RelatedProductDef properties populated.

Simple LINQ Query with LINQ to SQL, think I'm doing something wrong

I have a table in my LINQ to SQL portion of my project.
I'm just trying to perform a simple query like so:
public static string GetMLBID(int fk_players_id)
{
using (MLBDataClassesDataContext context = new MLBDataClassesDataContext())
{
var query = from a in context.players
where a.fk_player_type_id == fk_players_id
select a.mlb_com_id;
foreach (var b in query)
{
Console.WriteLine(b.); //<-- I don't get the properties listed in the "players" table that i linked in the imgur link.
}
}
}
From all the examples in google.. where i have "b.", the properties from the table i have should be popping up.. but that's not listed. i only get simple LINQ operators and methods.
I feel like i'm missing something really simple.. any help?
You are only selecting the id mlb_com_id
select a.mlb_com_id;
Change the select clause to
select a;
This allows you to access all the public members of a on the result set.
EDIT by Pellared. (The point of Pellared's addition is that the extension method syntax does not require a Select-clause and would therefore not have lead to the error):
You can also change the query using lamba expressions (which a lot of people prefer)
public static string GetMLBID(int fk_players_id)
{
using (MLBDataClassesDataContext context = new MLBDataClassesDataContext())
{
var query = context.players
.Where(a => a.fk_player_type_id == fk_players_id);
foreach (var b in query)
{
Console.WriteLine(b.mlb_com_id);
}
}
}
You need to get your elements as a list and you should be able to access the properties then.
public static string GetMLBID(int fk_players_id) {
using (MLBDataClassesDataContext context = new MLBDataClassesDataContext())
{
var query = (from a in context.players
where a.fk_player_type_id == fk_players_id
select a).ToList();
foreach (var b in query)
{
Console.WriteLine(b.first_name);
}
}
}

How can I use linq to search inside a list of objects

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);

Problem with order by in LINQ

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.

Categories