How do Group by a child property of a child property that may be null? - linq

How could I go about grouping the following?
people.GroupBy(p=>p.Addresses.GetFirstOrDefault().State);
without it failing on people who don't have an Address?
can it be done in one statement?
if not, do I have to first get a Distinct() list of all the various addresses members? How? (actually -- even if a is possible -- would be great to also learn how to do b :-) )
I havn't seen it, but is there something equivalent to a GetFirstOrNew() that can be used to instantiate and return a non-null?
Thank you very much!

It can be done in one statement, yes:
// Set up whatever you need
Address dummyAddress = new Address { State = "" };
people.GroupBy(p => (p.Addresses.GetFirstOrDefault() ?? dummyAddress).State);
Alternatively, you might want to write a helper method:
public string GetState(Address address)
{
return address == null ? null : address.State;
}
Then you can use:
people.GroupBy(p => GetState(p.Addresses.GetFirstOrDefault()));

Related

Search IList of KeyValuePairs for two keys

I am putting in a temporary fix to code in which we want to validate attributes on an item. These are "swatchImageUrl" and "swatchVariantAttribute". If either one of these is provided, the other must be provided. Where I will check this is on a dictionary of the values. So what I have in place is the following:
if((transformedValues.Any(t => t.Key.Equals("swatchImageUrl")) &&
!transformedValues.Any(t => t.Key.Equals("swatchVariantAttribute"))) ||
(transformedValues.Any(t => t.Key.Equals("swatchVariantAttribute")) &&
!transformedValues.Any(t => t.Key.Equals("swatchImageUrl"))))
{
// throw an error here
}
This feels clunky and possibly inefficient (transformedValues will possibly be a very large list and my understanding is .Any() will end up enumerating the whole list if there are none) but I cannot think of a nicer way of doing this. 'transformedItems' is an IList of string key value pairs (so I can't use .ContainsKey etc.)
Is there some nice neater way of doing this that I am missing? Any insight is much appreciated.
Just in case anyone else is having similar brainfreeze. The obvious way to do this in a better way is as ASh pointed out;
if(transformedValues.Any(t => t.Key.Equals("swatchImageUrl")) != transformedValues.Any(t => t.Key.Equals("swatchVariantAttribute")))
{ /*...*/ }

Accessing deeply nested table without error?

For a field inside a deeply nested table, for example, text.title.1.font. Even if you use
if text.title.1.font then ... end
it would result in an error like "attempt to index global 'text' (a nil value)" if any level of the table does not actually exists. Of course one may tried to check for the existence of each level of the table, but it seems rather cumbersome. I am wondering is there a safe and prettier way to handle this, such that when referencing such an object, nil would be the value instead of triggering an error?
The way to do this that doesn't invite lots of bugs is to explicitly tell Lua which fields of which tables should be tables by default. You can do this with metatables. The following is an example, but it should really be customized according to how you want your tables to be structured.
-- This metatable is intended to catch bugs by keeping default tables empty.
local default_mt = {
__newindex =
function()
error(
'This is a default table. You have to make nested tables the old-fashioned way.')
end
}
local number_mt = {
__index =
function(self, key)
if type(key) == 'number' then
return setmetatable({}, default_mt)
end
end
}
local default_number_mt = {
__index = number_mt.__index,
__newindex = default_mt.__newindex
}
local title_mt = {__index = {title = setmetatable({}, default_number_mt)}}
local text = setmetatable({}, title_mt)
print(text.title[1].font)
Egor's suggestion debug.setmetatable(nil, {__index = function()end}) is the easiest to apply. Keep in mind that it's not lexically scoped, so, once it's on, it will be "on" until turned off, which may have unintended consequences in other parts of your code. See this thread for the discussion and some alternatives.
Also note that text.title.1.font should probably be text.title[1].font or text.title['1'].font (and these two are not the same).
Another, a bit more verbose, but still usable alternative is:
if (((text or {}).title or {})[1] or {}).font then ... end

Why/How to use passed constants in function?

I've seen classes where constants are passed to methods, I guess its done to define some kind of setting in that function. I cant find it anywhere now to try to find out the logic, so I though I could ask here. How and why do you use this concept and where can I find more information about it?
The example below is written in PHP, but any language that handles constants would do I guess..
// Declaring class
class ExampleClass{
const EXAMPLE_CONST_1 = 0;
const EXAMPLE_CONST_2 = 1;
function example_method($constant(?)){
if($constant == ExampleClass::EXAMPLE_CONST_1)
// do this
else if($constant == ExampleClass::EXAMPLE_CONST_2)
// do that
}
}
// Using class
$inst = new ExampleClass();
$inst->example_method(ExampleClass::EXAMPLE_CONST_1);
To me its more clear to pass "ExampleClass::EXAMPLE_CONST_1" than to just pass "1", but it's that the only reason to pass constant?
Simply passing 1 doesn't say much. By having a constant you can have a description about the settings in the name.
example:
constant RAIN = 1;
method setWeather(RAIN);
Atleast that's how and why I use it.
It is always a good idea to avoid literals being passed around. By assigning a name, anyone reading your code has a chance to understand what that value means - a number has no meaning. It might also help you maintaining your code: If for some requirement the value has to be changed, you can easily do it in one place, instead of checking each and every value occurrence.

How to use Enumerations in DXL Scripts?

I'd like to test the value of an enumeration attribute of a DOORs object. How can this be done? And where can I find a DXL documentation describing basic features like this?
if (o."Progress" == 0) // This does NOT work
{
// do something
}
So after two weeks and an expired bounty I finally made it.
Enum-Attributes can be assigned to int or string variables as desired. But you have to assign to a variable to perform such a conversion. It is not casted when a mere comparison is done like in my example. So here comes the solution:
int tmp = o."Progress"
if (tmp == 0)
{
// do something
}
When tmp is a string, a comparison to the enum literals is possible.
That was easy. Wasn't it? And here I finally found the everything-you-need-to-know-about-DXL manual.
For multi-valued enumerations, the best way is if (isMember(o."Progress", "0")) {. The possible enumerations for single and multi-enumeration variables are considered strings, so Steve's solution is the best dxl way for the single enumeration.
You can also do
if(o."Progress" "" == "0")
{
//do something
}
This will cast the attribute value to a string and compare it to the string "0"
If you're talking about the "related number" that is assignable from the Edit Types box, then you'll need to start by getting the position of the enumeration string within the enum and then retrieve EnumName[k].value .
I'm no expert at DXL, so the only way to find the index that I know of off the top of my head is to loop over 1 : EnumName.size and when you get a match to the enumeration string, use that loop index value to retrieve the enumeration "related number."

Which syntax is better for return value?

I've been doing a massive code review and one pattern I notice all over the place is this:
public bool MethodName()
{
bool returnValue = false;
if (expression)
{
// do something
returnValue = MethodCall();
}
else
{
// do something else
returnValue = Expression;
}
return returnValue;
}
This is not how I would have done this I would have just returned the value when I knew what it was. which of these two patterns is more correct?
I stress that the logic always seems to be structured such that the return value is assigned in one plave only and no code is executed after it's assigned.
A lot of people recommend having only one exit point from your methods. The pattern you describe above follows that recommendation.
The main gist of that recommendation is that if ou have to cleanup some memory or state before returning from the method, it's better to have that code in one place only. having multiple exit points leads to either duplication of cleanup code or potential problems due to missing cleanup code at one or more of the exit points.
Of course, if your method is couple of lines long, or doesn't need any cleanup, you could have multiple returns.
I would have used ternary, to reduce control structures...
return expression ? MethodCall() : Expression;
I suspect I will be in the minority but I like the style presented in the example. It is easy to add a log statement and set a breakpoint, IMO. Plus, when used in a consistent way, it seems easier to "pattern match" than having multiple returns.
I'm not sure there is a "correct" answer on this, however.
Some learning institutes and books advocate the single return practice.
Whether it's better or not is subjective.
That looks like a part of a bad OOP design. Perhaps it should be refactored on the higher level than inside of a single method.
Otherwise, I prefer using a ternary operator, like this:
return expression ? MethodCall() : Expression;
It is shorter and more readable.
Return from a method right away in any of these situations:
You've found a boundary condition and need to return a unique or sentinel value: if (node.next = null) return NO_VALUE_FOUND;
A required value/state is false, so the rest of the method does not apply (aka a guard clause). E.g.: if (listeners == null) return null;
The method's purpose is to find and return a specific value, e.g.: if (nodes[i].value == searchValue) return i;
You're in a clause which returns a unique value from the method not used elsewhere in the method: if (userNameFromDb.equals(SUPER_USER)) return getSuperUserAccount();
Otherwise, it is useful to have only one return statement so that it's easier to add debug logging, resource cleanup and follow the logic. I try to handle all the above 4 cases first, if they apply, then declare a variable named result(s) as late as possible and assign values to that as needed.
They both accomplish the same task. Some say that a method should only have one entry and one exit point.
I use this, too. The idea is that resources can be freed in the normal flow of the program. If you jump out of a method at 20 different places, and you need to call cleanUp() before, you'll have to add yet another cleanup method 20 times (or refactor everything)
I guess that the coder has taken the design of defining an object toReturn at the top of the method (e.g., List<Foo> toReturn = new ArrayList<Foo>();) and then populating it during the method call, and somehow decided to apply it to a boolean return type, which is odd.
Could also be a side effect of a coding standard that states that you can't return in the middle of a method body, only at the end.
Even if no code is executed after the return value is assigned now it does not mean that some code will not have to be added later.
It's not the smallest piece of code which could be used but it is very refactoring-friendly.
Delphi forces this pattern by automatically creating a variable called "Result" which will be of the function's return type. Whatever "Result" is when the function exits, is your return value. So there's no "return" keyword at all.
function MethodName : boolean;
begin
Result := False;
if Expression then begin
//do something
Result := MethodCall;
end
else begin
//do something else
Result := Expression;
end;
//possibly more code
end;
The pattern used is verbose - but it's also easier to debug if you want to know the return value without opening the Registers window and checking EAX.

Resources