I have a collection of data that has a collection called Approvals in it. The Approvals object has a property call ApplicationName. I want a list of all the Distinct Approvals ApplicationNames. So if I have a list of Approvals with applicationNames of Nick, Nick, Jack, Daniel I want to return the whole approval object of Nick, Jack, Daniel. Or at least just a list of the names Nick, Jack, Daniel
This isnt working for me..
theApplicationNames = theData.Approvals.Select(c => new WebsiteApplicationInfo
{
Name=c.ApplicationName,
ID=c.ApplicationId
}).Distinct().ToList();
If you want a list of the distinct names, you would use
var names = theData.Approvals.Select(a => a.ApplicationName).Distinct();
This would result in a list of all the names (presumably strings?).
One likely reason your version "isn't working" for you is that you are using .Distinct() on a collection of WebsiteApplicationInfo objects, which might not have a correct equality comparison implemented. Without knowing what you mean by "isn't working", though, we can't really be sure.
theData.Approvals.Select(a => a.ApplicationName).Distinct();
If you project a single property, you can just distinct on that. If you are projecting anonymous types, you either need to use the GroupBy trick or create a custom IComparer that you pass to the Distinct. You should be able to find quite a few solutions using the following search: https://stackoverflow.com/search?q=distinctby&submit=search
Related
I add a virtual column, then I filter it using "having". When I need to filter by one value, all works fine, but I also need to filter by "not null". having expects only 3 arguments, including the clause, the value and the binding type, is there any way to pass in a criteria?
$Sharings->having("TotalSharing = ?",2, \PDO::PARAM_INT);
Or do I have to add a new virtual column who has as value what I need directly?
Thanks a lot in advance!
Gioia
Ok, was actually a lot easier then I thought, I just used:
$Sharings->having("TotalSharing > ?",0, \PDO::PARAM_INT);
So I didn't need to use a Criteria object, silly of me not to think about this, just so used to use filterBy...
I need to find whether a specific attribute is present or not with where statement that takes an array in ruby.
I tried like the below.
User.where(id: [1,2,3]).include?('address')
User.where(id: [1,2,3]) would return a relation (which behaves pretty much as an array, but that's another story). It means, that is consists of objects - instances of User class.
You check if this collection includes string ('address'). It is not, as you may guess by now.
If you need to map all users by address, you can use pluck:
User.where(id: [1,2,3]).pluck(:address)
You could use: User.where(id: [1,2,3]).map(&:address) which will return an array containing the addresses.
And you can use User.where(id: [1,2,3]).map(&:address).map(&:present?) if you want an array with true or false value
I have an array of users who are managers.
However there are repeated Users.
I would like to group them so that there is only one instance of each User in the array.
What would be the best way to go about this?
#managers.sort_by{|obj| obj.id} # Just sorted the data but did not eliminate duplicats
#managers.group_by{|u|u.name} # just created a bunch of arrays for each name
Use the uniq method, which returns a new array with duplicates removed.
#managers.uniq
If by duplicate you mean the same object ID, then you can do the following:
#managers.uniq.group_by(&:name)
Filtering the array feels like fixing symptoms. Why does the array contain rubbish in the first place?
I would suggest adding a manager? method to your User model that returns true if the user is a manager. Then you could to something like
#managers = User.select &:manager?
and get an array that only contains managers.
you can also do
Manager.select('DISTINCT user_id')
to get a clean array in the first place, whith better performance.
Most of the examples I've found deal with Linq to entities, which is not what I need. I have a standard DataTable which I need to modify before returning to the caller. I can iterate over the normal Table.Rows collection or do something like this with the new extension methods:
foreach (var x in table.AsEnumerable()) {
if (x.Field<int>("SomeField") > SomeValue)
x.SetField<string>("OtherField", "OtherValue");
}
But I'm still manually looping through the entire row collection. Not necessarily a big deal, but I'm wondering if there's a more elegant way to accomplish this with Linq somehow, in the sense that I need to create an expression that iterates over the results of a query and performs an arbitrary action, rather than just select elements from the container being enumerated.
I think what you're wondering is if there's some sort of extension method like
stuff.ForEach(x => x.Value = "new value");
Unfortunately, there is no such thing. When I began using LINQ to SQL, I wanted the same thing. But unfortunately, you must use a for loop.
we had a heated discussion about a method name.
We have a class User. There is property called "Groups" on the user. It contains all groups that contain the user directly. That's ok. What we have problem with, is the name of the method that would recursively list all user's groups and their "parent" groups and return list of all groups, of which the user can be considered as member.
User u = <get user>;
IList<UserGroup> groups = u.XYZ();
Console.WriteLine("User {0} is member of: ", u);
foreach(UserGroup g in groups)
Console.WriteLine("{0}", g);
My colleagues brought:
u.GetAllGroups(); // what groups?
u.GetMemberOfGroups(); // doesn't make sense
u.GroupsIAmMemberOf(); // long
u.MemberOf(); // short, but the description is wrong
u.GetRolesForUser(); // we don't work with roles, so GetGroupsForUser ?
u.GetOccupiedGroups(); // is the meaning correct?
What name would you propose?
In the interests of high cohesion and low coupling, I would suggest keeping that functionality out of your User class entirely. It should also be easier to implement caching for multiple calls if that functionality was in a different class.
For example:
User u = <get user>;
IList<UserGroup> groups = SecurityModel.Groups.getMembership(u);
You then have the option to cache the group/user memberships in the Groups object, improving efficiency for future group membership requests for other users.
I think I would choose:
u.GetGroupMembership()
u.GetGroups()
unless there was some ambiguity about the meaning of groups in your application, i suppose. (i like typing less when possible!)
Given that there are no parameters, I suggest a property e.g.
u.Groups;
or
u.UserGroups; // if Groups is ambiguous
if (the signature of the property Groups cannot be changed)
{
I think you are screwed
and the best thing I can think of
is another property named AllGroups
// u.Groups and u.GetWhatever() look very inconsistently
}
else
{
if (you are okay with using the term "group")
{
I would select one of these variants:
{
a pair of properties named ParentGroups and AncestorGroups
}
or
{
a parameterized method or property Groups(Level)
where Level can be either PARENTS (default) or ANCESTORS
}
}
else
{
I would consider replacing "group" with "membership"
and then I would select one of these variants:
{
a pair of properties named DirectMemberships and AllMemberships
}
or
{
a parameterized method or property Memberships(Level)
where Level can be either DIRECT_ONLY (default) or ALL
}
}
}
Does any of this make any sense? ;-)
I agree with Greg, but would make it simpler:
u.GroupMembership();
I think appending the verb Get is kind of useless, given
the return type (List of Groups)
I'm from Stej's team:-) There is already property called "Groups" on the user. It contains all groups that contain the user directly. That's ok.
What we have problem with, is the name of the method that would recursively list all user's groups and their "parent" groups and return list of all groups, of which the user can be considered as member.
Depending on what environment you guys are working in, you may be able to leverage existing frameworks for this sort of thing rather than rolling your own. If you are using .NET 2.0 or higher, I'd suggest leveraging the System.Web.Security.RoleProvider class. A previous answer of mine has more thoughts on this here.
Roles are flat, we need something more powerful. We don't want to be bound to web environment either.