Last post May 16, 2019 02:19 PM by bruce (sqlwork.com)
May 15, 2019 05:55 PM|joegreen2005|LINK
I have collection of objects returned from database. I want to check if the values of two attributes are same or different in this collection. I'm trying with just one attribute and here is my code but every time, I run, sameLength is "different" even though
the value if the Length attribute is same for all items in the collection. When I run a SQL query with Distinct, I get just one record. Any idea what mistake am I making.
string val = group.First().Length;
string sameLength = group.All(s => s.Length == val) ? "same" : "different";
My other question is how should I do this for 2 attributes together Length and Length Unit?
May 16, 2019 07:19 AM|AddWeb Solution|LINK
Try This way
bool same = false;
var first = items.FirstOrDefault();
if (first != null) // assuming it's a class
same = items.Skip(1).All(i => i.Template.Frequency == first.Template.Frequency);
bool same = false ;
Item first = null;
foreach(var item in items)
if (first == null)
first = item;
same = true;
if (item.Template.Frequency != first.Template.Frequency)
same = false;
May 16, 2019 07:59 AM|PatriceSc|LINK
And in your group you have an object or a string? I wonder if it couldn't be some confusion with String.Length (as it seems you really don't expect the result you get)?
My understanding is that you want to know if all rows are sharing the same attribute values? Another approach would be to just group rows based on the attribute(s) you want and see if you have a single group. Plus the result allows to list all the different
combinations you actually found.
Edit: for example https://code.msdn.microsoft.com/LINQ-to-DataSets-Grouping-c62703ea
according to the name of the source it is already a group by not on the same attributes ? (you can still group on this group).
May 16, 2019 12:49 PM|joegreen2005|LINK
I'm trying to check the value of a column in the group of rows.
I'm trying grouping the group like this but count of result is still 2but when I run the SQL query against database I get just one value as expected. Here is what I tried
var result = group.GroupBy(s => s.Length).ToList().Distinct();
May 16, 2019 01:38 PM|mgebhard|LINK
Try going through the LINQ Group By reference.
Otherwise, share code that we can easily run without having to guess the object model.
May 16, 2019 01:58 PM|PatriceSc|LINK
Can you move the cursor on Length and check this is yourEntity.Length rather than String.Length ? I suspect that group is perhaps mistakenly a list of string in which case rather than working on a Length property on your entity you work on the Length of
May 16, 2019 02:19 PM|bruce (sqlwork.com)|LINK
there are a couple differences between SQL string compare and c# compare. sql will ignore case, and add trailing blanks, try:
string sameLength = group.All(s =>
) ? "same" : "different";