Apply Method to Each Elements in Array/Enumerable

Apply method to each elements in array/enumerable

This will work:

array.map!(&:to_s)

Performing function on each array element, returning results to new array

You can use Select() to transform one sequence into another one, and ToArray() to create an array from the result:

int[] numbers = { 1, 2, 3 };
string[] strings = numbers.Select(x => ToWords(x)).ToArray();

Apply function to all elements of collection through LINQ

A common way to approach this is to add your own ForEach generic method on IEnumerable<T>. Here's the one we've got in MoreLINQ:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
source.ThrowIfNull("source");
action.ThrowIfNull("action");
foreach (T element in source)
{
action(element);
}
}

(Where ThrowIfNull is an extension method on any reference type, which does the obvious thing.)

It'll be interesting to see if this is part of .NET 4.0. It goes against the functional style of LINQ, but there's no doubt that a lot of people find it useful.

Once you've got that, you can write things like:

people.Where(person => person.Age < 21)
.ForEach(person => person.EjectFromBar());

Executing a certain action for all elements in an Enumerable T

A quick-and-easy way to get this is:

Names.ToList().ForEach(e => ...);

How to run function for each element on arrays

I think your algorithm could be simplified quite a bit. In particular, breaking the latitudes and longitudes into separate arrays and then later using nested for loops to reunite them seems unnecessary. Here's a suggestion that skips those steps.

Note that this is totally untested, but it might get you well along the right track.

Other things to note are the possibility of using for...of instead of traditional for loops, using distance in the same scope in which it gets declared, and being ready for the situation where distance == .05.

function showPosition(position){
const userlocationLatitude = position.coords.latitude;
const userlocationLongitude = position.coords.longitude;
let success = function(res){
for(let location of res.locations){
let startPosLat = location['place_latitude'],
startPosLng = location['place_longitude'],
distance = calculateDistance(startPosLat, startPosLong, userlocationLatitude, userlocationLongitude);
if(distance < .05){ $('.div-image').attr('src', 'pic2.jpg'); }
else{ $('.div-image').attr('src', 'pic.jpg'); }
}
}
$.ajax({ type: 'GET', url: '/api/locations', crossDomain: true, dataType: 'json', async: false, success : success });

//function to calculate the distance between two points of coordinates
function calculateDistance(lat1, lon1, lat2, lon2) {
var R = 6371, dLat = (lat2-lat1).toRad(), dLon = (lon2-lon1).toRad(),
a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon/2) * Math.sin(dLon/2),
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
Number.prototype.toRad = function() { return this * Math.PI / 180; }
}

Ruby method call to each using include Enumerable

You have a typo. It's initialize, not initialise. Your @members instance var was never assigned to, that's why it's nil.

Apply function to each element of a list

Using the built-in standard library map:

>>> mylis = ['this is test', 'another test']
>>> list(map(str.upper, mylis))
['THIS IS TEST', 'ANOTHER TEST']

In Python 2.x, map constructed the desired new list by applying a given function to every element in a list.

In Python 3.x, map constructs an iterator instead of a list, so the call to list is necessary. If you are using Python 3.x and require a list the list comprehension approach would be better suited.

Passing Ruby array elements to a method

Take a look at the documentation for ruby's Enumerable, which arrays implement. What you're looking for is the map method, which takes each element of an enumerable (i.e. an array) and passes it to a block, returning a new array with the results of the blocks. Like this:

array.map{|element| resolve_name(element) }

As an aside, in your method, you do not need to use a local variable if all you're doing with it is returning its value; and the return statement is optional - ruby methods always return the result of the last executed statement. So your method could be shortened to this:

def resolve_name(ns_name)
Resolv.getaddress(ns_name)
end

and then you really all it's doing is wrapping a method call in another. So ultimately, you can just do this (with array renamed to ns_names to make it self-explanatory):

ns_names = ['ns-1.me.com', 'ns-2.me.com']
ip_addresses = ns_names.map{|name| Resolv.getaddress(name) }

Now ip_addresses is an array of IP addresses that you can use in your template.

Accessing elements of an Array (of any element type) from an object

second code:

int[] array = new int[] { 0, 1, 2 };
object obj=array;
var obj_array=(Array)obj;
IEnumerable<object> collection = obj_array.Cast<object>();
string output=string.join(", ",collection.Select(x=>x.ToString()));

so main code will be:

Dictionary<string,string>[] getInfo(string k) {
// using `k` as management-key
var mos = new ManagementObjectSearcher($"select * from {k}");
var devices = new List<Dictionary<string, string>>();
var mosc = mos.Get(); // mosc is a collection of all devices with same key
foreach (var device in mosc) {
var properties = new Dictionary<string, string>();
foreach (var p in device.Properties) {
if (p.Value != null) {
if (p.IsArray) {
var array = (Array)p.Value;
var collection = array.Cast<object>();
properties[p.Name] = string.Join(", ", collection.Select(x=>x.ToString()));
} else
properties[p.Name] = p.Value.ToString();
} else properties[p.Name] = "";
}
devices.Add(properties);
}
return devices.ToArray();
}


Related Topics



Leave a reply



Submit