MVC Linq .Random() wrong syntax - linq

Hello guys I have some problem with this code but not find something similar in knowledgeBase:
#foreach (var prodotti in contesto.Prodotti.Where(x => x.ProdottoVisibile == true).OrderByDescending(x => x.ProdottoID).Random().Take(5))
it seems .Random() is not working, should i have to manage differently ? of course YES, but how?
anyone can give me an tips?
thx a lot!

you can define a variable with your list of records :
var prodotti = contesto.Prodotti.Where(x => x.ProdottoVisibile ==
true).OrderByDescending(x => x.ProdottoID)
//define Random variable
var random = new Random();
int index = random.Next(prodotti.Count);
//This line should return 5 random records from the list
prodotti.OrderBy(x => rnd.Next()).Take(5);

Related

Update a value from linq query

I am in the middle of an api integration and i have to update something from linq query.
var t = availabilityRs.hotels.hotels.Select(c => c.rooms.Select(h =>
h.rates.Select(y => { y.net = y.net*2;return y; })) ).ToList();
This is the query i wrote.
I want to update the net in the end of the object tree and assign it to var t. But this query doesn't update it. I wanna know what's wrong with this code.
Thank you
Guys thank you for the help. Kara your answer isn't the exact answer for my question but it was a big help to me to form my answer. Thanks alot!
This is my answer..
availabilityRs.hotels.hotels.ToList().ForEach
(c => c.rooms.ToList().ForEach
(h => h.rates.ForEach
(f => f.net = (int)Math.Round((f.net * rates), 0))));
Select retrieves some values. What you want to do is a ForEach.
var tmp = availabilityRs.hotels.hotels.Select(c => c.rooms.Select(h => h.rates.ToList();
tmp.ForEach(y => y.net *= 2);

How do I Sort/OrderBy IList<Int32>

I'm trying Sort on IList, I have tried different approach but none works
here is what my code looks like:
IList<IWebElement> listCountIdsUi = driver.FindElements(By.CssSelector("table#ct_ tr td:nth-of-type(1)"));
List<Int32> ui = new List<Int32>();
foreach (IWebElement option in listCountIdsUi)
{
if (!option.Text.ToString().StartsWith("Page"))
{
ui.Add(Convert.ToInt32(option.Text));
}
}
the only way I able to figured out is working with ArrayList
ArrayList al = new ArrayList(ui);
al.Sort();
is not possible using IList ?
OrderBy does NOT modify the underlying collection - it returns an IEnumerable that gives you the items in the order you ask for. So you have a few options:
Use List.Sort(), which does modify the underlying collection:
ui.Sort();
Store the sorted list in a new variable
var uiSorted = ui.OrderBy(s => s);
replace the existing reference
ui = ui.OrderBy(s => s).ToList();
Have you tried the List<T>.Sort method?
ui.Sort((a, b) => a.CompareTo(b));
var uiOrdered = ui.OrderBy(s => s).ToList() should be all you need to do.

LINQ Group By into a Dictionary Object

I am trying to use LINQ to create a Dictionary<string, List<CustomObject>> from a List<CustomObject>. I can get this to work using "var", but I don't want to use anonymous types. Here is what I have
var x = (from CustomObject o in ListOfCustomObjects
group o by o.PropertyName into t
select t.ToList());
I have also tried using Cast<>() from the LINQ library once I have x, but I get compile problems to the effect of it being an invalid cast.
Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
.GroupBy(o => o.PropertyName)
.ToDictionary(g => g.Key, g => g.ToList());
I cannot comment on #Michael Blackburn, but I guess you got the downvote because the GroupBy is not necessary in this case.
Use it like:
var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]
Additionally, I've seen this perform way better than when using GroupBy().ToDictionary().
For #atari2600, this is what the answer would look like using ToLookup in lambda syntax:
var x = listOfCustomObjects
.GroupBy(o => o.PropertyName)
.ToLookup(customObject => customObject);
Basically, it takes the IGrouping and materializes it for you into a dictionary of lists, with the values of PropertyName as the key.
This might help you if you to Get a Count of words. if you want a key and a list of items just modify the code to have the value be group.ToList()
var s1 = "the best italian resturant enjoy the best pasta";
var D1Count = s1.ToLower().Split(' ').GroupBy(e => e).Select(group => new { key = group.Key, value = group.Count() }).ToDictionary(e => e.key, z => z.value);
//show the results
Console.WriteLine(D1Count["the"]);
foreach (var item in D1Count)
{
Console.WriteLine(item.Key +" "+ item.Value);
}
The following worked for me.
var temp = ctx.Set<DbTable>()
.GroupBy(g => new { g.id })
.ToDictionary(d => d.Key.id);

LINQ: Field is not a reference field

I've got a list of IQueryable. I'm trying to split this list into an array of IQueryable matching on a certain field (say fieldnum) in the first list...
for example, if fieldnum == 1, it should go into array[1]. I'm using Where() to filter based on this field, it looks something like this:
var allItems = FillListofMyObjects();
var Filtered = new List<IQueryable<myObject>(MAX+1);
for (var i = 1; i <= MAX; i++)
{
var sublist = allItems.Where(e => e.fieldnum == i);
if (sublist.Count() == 0) continue;
Filtered[i] = sublist;
}
however, I'm getting the error Field "t1.fieldnum" is not a reference field on the if line. stepping through the debugger shows the error actually occurs on the line before (the Where() method) but either way, I don't know what I'm doing wrong.
I'm farily new to LINQ so if I'm doing this all wrong please let me know, thanks!
Why don't you just use ToLookup?
var allItemsPerFieldNum = allItems.ToLookup(e => e.fieldnum);
Do you need to reevaluate the expression every time you get the values?
Why not use a dictionary?
var dictionary = allItems.ToDictionar(y => y.fieldnum);

LINQ QUery: Take () based upon textbox value

I am creating a gridview that will be populated based upon a linq statement, the sql is as follows:
SELECT TOP 10 IDDesc, UnitUserfield1, UnitUserfield2, ProductPercentage
FROM tblOnlineReportingCOMPLETEWeights
WHERE (MaterialLevel = 'Primary') AND (MaterialText = 'Paper')
ORDER BY ProductPercentage DESC
Now, what I would like to do is let the user specify the Top 10, so essentially it is a "Top x" this being defined in a textbox i.e. they type in 50 into the textbox, the linq query is executed and the gridview displays the top 50.
I understand that using Take is the area I want to look at, is this correct? Is this even possible?!
Any thoughts, muchly appreciated.
PS: apologies for asking thick questions, I am very new to all of this!
You are correct. Take user input and feed it to Take. That'll do.
int howMany = Convert.ToInt32 (HowManyTextBox.Value);
var queryResult = /*.....*/.Take (howMany);
int max = 0;
if (Int.TryParse(TextBox1.Text, out max)
{
var q = (from tbl where ... orderby ... desc).Take(max);
}
Along those lines
Thank you all so much, I went with the following:
{
ORWeightsDataClassesDataContext db = new ORWeightsDataClassesDataContext();
int max = 0;
if (int.TryParse(txtbxHowMany.Text, out max))
{
var queryV = db.tblOnlineReportingCOMPLETEWeights
.Where(x => x.MaterialLevel == "Primary" && x.MaterialText == "Paper")
.OrderByDescending(x => x.ProductPercentage).Take(max);
GridView1.DataSource = queryV;
GridView1.DataBind();
}
}
It works a treat.
Thank so so much, very grateful and now my site is finally coming together...I feel liek celebrating...pub anyone?!

Resources