C
C#7mo ago
Muhammad

❔ ✅ Mind explaining a code to me?

public static int? Closest(int[] arr)
{
var min = arr.Distinct().Where(x => Math.Abs(x) == arr.Min(Math.Abs));
return min.Count() == 1 ? min.First() : (int?) null;
}
public static int? Closest(int[] arr)
{
var min = arr.Distinct().Where(x => Math.Abs(x) == arr.Min(Math.Abs));
return min.Count() == 1 ? min.First() : (int?) null;
}
67 Replies
Angius
Angius7mo ago
It's a bunch of LINQ code .Distinct() gets only unique elements .Where() filters the collection by the predicate .Count() gets the amount of items in the collection .First() gets the first element condition ? iftrue : iffalse is a ternary expression
Muhammad
Muhammad7mo ago
removes duplicates
Angius
Angius7mo ago
x => stuff is a lambda
Muhammad
Muhammad7mo ago
i don't get this meaning? but idk what it means in this context
MODiX
MODiX7mo ago
Angius
REPL Result: Success
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.Where(number => number % 2 == 0)
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.Where(number => number % 2 == 0)
Result: WhereArrayIterator<int>
[
2,
4,
6,
8,
10
]
[
2,
4,
6,
8,
10
]
Compile: 574.081ms | Execution: 98.215ms | React with ❌ to remove this embed.
Muhammad
Muhammad7mo ago
filters with a condition i thought => was to return a value
MODiX
MODiX7mo ago
Angius
REPL Result: Success
int[] numbers = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
foreach(int number in numbers)
{
string message = number % 2 == 0 ? "even" : "odd";
Console.WriteLine($"Number {number} is {message}");
}
int[] numbers = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
foreach(int number in numbers)
{
string message = number % 2 == 0 ? "even" : "odd";
Console.WriteLine($"Number {number} is {message}");
}
Console Output
Number 1 is odd
Number 2 is even
Number 3 is odd
Number 4 is even
Number 5 is odd
Number 6 is even
Number 7 is odd
Number 8 is even
Number 9 is odd
Number 10 is even
Number 1 is odd
Number 2 is even
Number 3 is odd
Number 4 is even
Number 5 is odd
Number 6 is even
Number 7 is odd
Number 8 is even
Number 9 is odd
Number 10 is even
Compile: 782.019ms | Execution: 141.873ms | React with ❌ to remove this embed.
Angius
Angius7mo ago
Kinda-sorta The lambda number => number % 2 == 0 will return a boolean If that boolean is false, the element gets filtered out
Muhammad
Muhammad7mo ago
No description
Muhammad
Muhammad7mo ago
is number a made up var? number => number... that one
Angius
Angius7mo ago
number => number % 2 == 0;
number => number % 2 == 0;
is basically a shorter, anonymous version of
public bool DoSuff(int number)
{
return number % 2 == 0;
}
public bool DoSuff(int number)
{
return number % 2 == 0;
}
It's a parameter
Muhammad
Muhammad7mo ago
is it only for lists? like
Angius
Angius7mo ago
No, you can use a lambda whenever, wherever
Muhammad
Muhammad7mo ago
for (x in var_name){}
for (x in var_name){}
the
x
x
but in this context is it for lists
MODiX
MODiX7mo ago
Angius
REPL Result: Success
var sum = (int a, int b) => a + b;

sum(2, 4)
var sum = (int a, int b) => a + b;

sum(2, 4)
Result: int
6
6
Compile: 596.015ms | Execution: 63.795ms | React with ❌ to remove this embed.
Muhammad
Muhammad7mo ago
=> is for returning
Angius
Angius7mo ago
If you're talking about LINQ, the .Where() part, then it's for any IEnumerable Including lists It just happens to take a Func<T, bool> as a parameter
Muhammad
Muhammad7mo ago
so public static int? Closest(int[] arr) { var min = arr.Distinct().Where(x => Math.Abs(x) == arr.Min(Math.Abs)); return min.Count() == 1 ? min.First() : (int?) null; } that's saying Distinct removes all dupes math.abs(x) == arr.Min(Math.Abs)) the absolute value of x is equal to the minimum absolute value in the list?
Angius
Angius7mo ago
Yep
Muhammad
Muhammad7mo ago
so like
Angius
Angius7mo ago
.Where() removes all elements where that is not true
Muhammad
Muhammad7mo ago
yeah so it filters to the condition new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} in this list min abs value is 1 and the value of x is in the first iteration 1 yeah bro i'm so lost with the logic too like i was confused with
for (int x = 0; x < 100; x++){}
for (int x = 0; x < 100; x++){}
but i learned the first section is when you define x, next is the condition, and next is what happens when the condition is met without Distinct() would it still filter?
Angius
Angius7mo ago
Yeah
Muhammad
Muhammad7mo ago
or do you need Distinct() and Where() together so distinct removes dupes and where filters after dupes have been removed?
Angius
Angius7mo ago
Exactly
Muhammad
Muhammad7mo ago
shoot
Angius
Angius7mo ago
You can chain LINQ methods almost at will
Muhammad
Muhammad7mo ago
i'm basically new beginner i'm sixth form y12 next yr we gonna make websites so i gotta study c# a lot
Angius
Angius7mo ago
Well, lambdas and LINQ are definitely not beginner topics
Muhammad
Muhammad7mo ago
i have known lambda from time basics of it so to find the number closest to 0 find the smallest possible value in abs form that's literally it
softmek
softmek7mo ago
No description
Muhammad
Muhammad7mo ago
what's the point of all that when you're tryna find the number closest to 0
Muhammad
Muhammad7mo ago
No description
softmek
softmek7mo ago
Am just explaining your answer, You never sent your qn
Muhammad
Muhammad7mo ago
no i wasn't tryna be rude
softmek
softmek7mo ago
no worries, send the question
Muhammad
Muhammad7mo ago
what's min.Count() and min.First()
MODiX
MODiX7mo ago
akhahmed
Quoted by
From akhahmed
React with ❌ to remove this embed.
MODiX
MODiX7mo ago
Angius
REPL Result: Success
new int[]{1, 2, 3, 4, 5, 6}.Count()
new int[]{1, 2, 3, 4, 5, 6}.Count()
Result: int
6
6
Compile: 542.876ms | Execution: 51.420ms | React with ❌ to remove this embed.
Muhammad
Muhammad7mo ago
Simply find the closest value to zero from the list. Notice that there are negatives in the list. List is always not empty and contains only integers. Return None if it is not possible to define only one of such values. And of course, we are expecting 0 as closest value to zero.
MODiX
MODiX7mo ago
Angius
REPL Result: Success
new int[]{1, 2, 3, 4, 5, 6}.First()
new int[]{1, 2, 3, 4, 5, 6}.First()
Result: int
1
1
Compile: 541.726ms | Execution: 67.039ms | React with ❌ to remove this embed.
Muhammad
Muhammad7mo ago
o
Angius
Angius7mo ago
I highly recommend trying to run the code and observing the results lol Learning by doing and all that jazz
Muhammad
Muhammad7mo ago
why is he doing min.Count ==1 i know i receive so many
Angius
Angius7mo ago
Checking if the collection has only a single element
Muhammad
Muhammad7mo ago
errors cause they put it in a clas s
Angius
Angius7mo ago
If it does, then that element is the closest to zero If there's more, that means there are more elements just as close to zero
softmek
softmek7mo ago
sending my solution in a sec, i'll create a function and explain in comments public static int? Closest(int[] arr) { int closestAbsoluteValue = arr.Select(Math.Abs).Min(); // Find the minimum absolute value var closestValues = arr.Where(x => Math.Abs(x) == closestAbsoluteValue); // Find values with the closest absolute value if (closestValues.Count() == 1) { return closestValues.First(); // If only one closest value found, return it } else { return null; // If multiple values with the same absolute value exist, return None } }
Angius
Angius7mo ago
$code
MODiX
MODiX7mo ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
Muhammad
Muhammad7mo ago
$code
public static int? Closest(int[] arr)
{
int closestAbsoluteValue = arr.Select(Math.Abs).Min(); // Find the minimum absolute value

var closestValues = arr.Where(x => Math.Abs(x) == closestAbsoluteValue); // Find values with the closest absolute value

if (closestValues.Count() == 1)
{
return closestValues.First(); // If only one closest value found, return it
}
else
{
return null; // If multiple values with the same absolute value exist, return None
}
}
public static int? Closest(int[] arr)
{
int closestAbsoluteValue = arr.Select(Math.Abs).Min(); // Find the minimum absolute value

var closestValues = arr.Where(x => Math.Abs(x) == closestAbsoluteValue); // Find values with the closest absolute value

if (closestValues.Count() == 1)
{
return closestValues.First(); // If only one closest value found, return it
}
else
{
return null; // If multiple values with the same absolute value exist, return None
}
}
MODiX
MODiX7mo ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
Muhammad
Muhammad7mo ago
public static int? Closest(int[] arr)
{
int closestAbsoluteValue = arr.Select(Math.Abs).Min(); // Find the minimum absolute value

var closestValues = arr.Where(x => Math.Abs(x) == closestAbsoluteValue); // Find values with the closest absolute value

if (closestValues.Count() == 1)
{
return closestValues.First(); // If only one closest value found, return it
}
else
{
return null; // If multiple values with the same absolute value exist, return None
}
}
public static int? Closest(int[] arr)
{
int closestAbsoluteValue = arr.Select(Math.Abs).Min(); // Find the minimum absolute value

var closestValues = arr.Where(x => Math.Abs(x) == closestAbsoluteValue); // Find values with the closest absolute value

if (closestValues.Count() == 1)
{
return closestValues.First(); // If only one closest value found, return it
}
else
{
return null; // If multiple values with the same absolute value exist, return None
}
}
$code
MODiX
MODiX7mo ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
softmek
softmek7mo ago
look, good
Muhammad
Muhammad7mo ago
i copied yours 💀 ofc i'm not gonna use it tho
softmek
softmek7mo ago
No description
Muhammad
Muhammad7mo ago
var closestValues = arr.Where(x => Math.Abs(x) == closestAbsoluteValue); // Find values with the closest absolute value
var closestValues = arr.Where(x => Math.Abs(x) == closestAbsoluteValue); // Find values with the closest absolute value
last thing i wanna know why is he tryna find the values with the closest abs value
softmek
softmek7mo ago
No description
Angius
Angius7mo ago
Because -2 is as close to zero as +2
Muhammad
Muhammad7mo ago
oh wait wait
Angius
Angius7mo ago
So you need to treat negative and positive values the same, in terms of proximity to 0
softmek
softmek7mo ago
So, by finding the values with the closest absolute value to zero, the function determines which number or numbers are closest to zero, considering both positive and negative numbers equally in their proximity to zero. If there's a unique value that's closest to zero, the function returns that value. If multiple values share the same closest absolute distance to zero, it indicates that there's no singular closest value to zero, so the function returns None.
Muhammad
Muhammad7mo ago
shoot shoot shoot public static int? Closest(int[] arr) { var min = arr.Distinct().Where(x => Math.Abs(x) == arr.Min(Math.Abs)); return min.Count() == 1 ? min.First() : (int?) null; } Distince() removes all dupes, Where()... sorts it out so only the smallest value is left, there would be 2 values left if there was a negative variant. IF there is either positive or negative, it will min.First(), and if there are 2 values with equal prox ( e.g. -2, 2 ) then it returns null?
return min.Count() == 1 ? min.First() : (int?) null;
return min.Count() == 1 ? min.First() : (int?) null;
why can't it be
return min.Count() == 1 ? min.First() : null;
return min.Count() == 1 ? min.First() : null;
Math.Abs holds all unique integers, and when == is set, it makes the list smaller because basically a condition has been set where it's equal to the min abs value perfect, thank you so much :))) !close
Accord
Accord7mo ago
Closed!
softmek
softmek7mo ago
(int?) means it's a nullable integer value, null return emply. which means (int?) will not work for non-numerical values,
Accord
Accord7mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts
❔ (MVC web app) How can I handle exceptions/errors in this case?So I was thinking of placing all this code (the one inside the function) inside a try catch block, a❔ `<code>` xml docs not showing nicely in VSCodeI want to use `<code>` in my XML docs to provide examples documentation. However, extra `\` appears ❔ Console RPG GameHello. Im currently in middle school, and our project is to make an RPG game using console. Sadly we❔ ✅ Why am I getting error message CS0184?I am trying to compare the return type of a generic method, which produces the following warning. Ho❔ ✅ denary -> binary```cs using System.Data; static void Main(string[] args) { string ans = AddBinary(1, 2); Co❔ Entity framework migration problemI have problem with creating the migration. I get this error "The seed entity for entity type 'AuthoCS00012 The type is defined in an assembly that is not referenced. But that assembly it is referenceOtherwise if I remove that reference I am getting more than 100 errors, the moment I add that refereI need little help trying to make something like that clicks for this game to help me build somethinHello, I can't get this program to click as it jumps i try and try it won't click idk why but my py❔ EFCore Interceptor problemIn the MS documentation I see they're using the SaveChanges interceptor as: ```csharp public async V❔ Is Entity Framework still worth usingIt has been a good 10 years or so since I used EF. From what I recall, it was good for code first an