logo
down
shadow

Generic method to map objects of different types


Generic method to map objects of different types

By : user2956734
Date : November 22 2020, 03:03 PM
this one helps. Linq's Select is the equivalent of the map() function in other functional languages. The mapping function would typically not be called Predicate, IMO - predicate would be a filter which could reduce the collection.
You can certainly wrap an extension method which would apply a projection to map input to output (either of which could be be anonymous types):
code :
public static IEnumerable<TO> Map<TI, TO>(this IEnumerable<TI> seznam, 
                                          Func<TI, TO> mapper)
{
    foreach (var item in seznam)
        yield return mapper(item);
}
public static IEnumerable<TO> Map<TI, TO>(this IEnumerable<TI> seznam, 
                                          Func<TI, TO> mapper)
{
    return seznam.Select(mapper);
}
public static IEnumerable<object> Map<TI>(this IEnumerable<TI> seznam, Func<TI, object> mapper)
{
   // Same implementation as above
var words = new List<string>() { "Kočnica", "druga beseda", "tretja", "izbirni", "vodno bitje" };
var wordsMapped = words.Map(el => new { cela = el, končnica = el.Končnica(5) });
static class MyExtensions
{
    public static int Končnica(this int i, int someInt)
    {
        return i;
    }

    public static Foo Končnica(this Foo f, int someInt)
    {
        return f;
    }

    public static string Končnica(this string s, int someInt)
    {
        return s;
    }
}
var things = new List<object>
{ 
   "Kočnica", "druga beseda", 
    53, 
    new Foo() 
};

var mappedThings = things.Map(el => new 
{ 
     cela = el, 
     končnica = MyExtensions.Končnica(el, 5) 
     // Or el.Končnica(5) IFF it is a method on all types, else run time errors ...
})
.ToList();


Share : facebook icon twitter icon
Struggling to come up with a generic C# method that compares different types of numeric objects

Struggling to come up with a generic C# method that compares different types of numeric objects


By : Rick
Date : March 29 2020, 07:55 AM
hop of those help? You can't make any good use of generics, as you don't know the data type at compile time.
Just use the Convert class to convert any kind numeric data to double values:
code :
double min = Convert.ToDouble(base.MinValue);
double max = Convert.ToDouble(base.MaxValue);
double attempted = Convert.ToDouble(value);
Can't be as specific with Java generic field types as with generic method types?

Can't be as specific with Java generic field types as with generic method types?


By : user2077792
Date : March 29 2020, 07:55 AM
it helps some times If you need to define a field with explicit parameter E like that, then you may have to parameterize the type in which the field is declared in. Something like this compiles:
code :
class MyClass<E extends Enum<E>> {
    Class<E> enumClass;
}
Call generic Method with multiple generic Types without specifying every single generic Type

Call generic Method with multiple generic Types without specifying every single generic Type


By : Giri
Date : March 29 2020, 07:55 AM
I wish this helpful for you In C#, there is no partial type inference: You must either specify all or none of the generic arguments, but the latter only works if the compiler is able to infer all types from context. Return types cannot be infered (except for some special cases such as lambdas), so what you want to do is not possible.
Two workarounds:
code :
class Example<T1>
{
    T1 GenericMethod<T2, T3>(T2 parameter1, T3 parameter2)
class Example
{
    T1 GenericMethod<T1>(object parameter1, object parameter2)
Correct generic types for adding objects to lists in a method

Correct generic types for adding objects to lists in a method


By : ThExcaliburW
Date : March 29 2020, 07:55 AM
it should still fix some issue If you change the signature of your method to void addToListAndSetId(List, SVGShape shape), it doesn't allow additions to the List, since nothing is stopping you from passing to the method a List with a SVGRectangle (which you shouldn't be able to add to that List).
You can add a generic type parameter to your method:
code :
private <T extends SVGShape> void addToListAndSetId(List<T> shapeList, T shape) {
    shapeList.add(shape);
    // more logic here
    shape.setId(shape.getLocalName().toLowerCase() + shapeList.size());
}
Generic method returning objects of generic derrived types

Generic method returning objects of generic derrived types


By : xirritate
Date : March 29 2020, 07:55 AM
I hope this helps you . Any time you have code using a generic type or method, and that code does some sort of test on the generic type parameter, you're doing it wrong. (And IMHO it goes without saying that dropping into reflection is even worse.) The whole point of a generic type is to write code that doesn't depend on the generic type.
In your example, a better approach would be something like this:
Related Posts Related Posts :
  • How to use Addfields in MongoDB C# Aggregation Pipeline
  • MsTest TestCleanup method not called when an unhandled exception is thrown
  • missing last data when exporting gridview to excel
  • How to add array of objects to List in c#
  • Lambda Expression to order (sort) my list collection
  • Library for displaying music notation
  • How to compare two dictionaries in c# and get the output as True and False after validation
  • specify fields to be serialized with JSON
  • How do you obtain the content of a specific node using XmlDocument in C#?
  • How to ignore the first line in a csv file when you read the csv file in C#
  • c# - Problem calling public void from class
  • How to tell a class which objects it should create? Type vs. object confusion :(
  • Save CheckBox state to xml
  • WIX CAQuietExec NETSH Command Fails
  • Issues sending http put request every 60 seconds to RoR app
  • ConfigurationManager.ConnectionStrings.ConnectionString Issue
  • Real size WPF controls for printing
  • How to cancel properly?
  • C# String multiplication error
  • Using Solrnet and Assigning Attributes with Entity Framework Generated POCOs
  • Regex pattern for single backslash
  • TextBox: insert spaces for credit card number?
  • C# DLL loaded for exe-application is not found when launching similar DLL by rundll32.exe
  • Debug a Windows Service with WCF library
  • Open a file from an external assembly?
  • Servicestack RegistrationFeature Unable to bind request
  • Index was outside the bounds of the array confusion
  • Error in Xml to List code. The ':' character, hexadecimal value 0x3A, cannot be included in a name
  • I am trying to do a while loop with a string conditional statement in C#
  • C# 'Cannot access a disposed object. Object name: 'SslStream'.'
  • How to make Gecko use seperate CookieContainer per instance?
  • C# Advanced form "please wait"
  • Send and Receive data C# using network stream
  • How to discover that appsettings changed in C#?
  • Check what needs full trust
  • What is the execution order of an MVC Razor view/layout
  • Table designer (Entity Framework) is too resource intense
  • How to clean up an exception string so it can be displayed via Javascript Alert?
  • Configuring Amazon SES Feedback Notifications via Amazon SNS in ASP.NET MVC (C#)
  • C# api responce and request
  • Dynamodb putitem function not working properly
  • theme in windows phone(light or dark) using c#
  • Backup attached database file(.mdf) using c# and SQL Server
  • What is 'TextFile' and where it is uses in WPF project
  • Using same alias for multiple namespaces
  • how to move mails into separate folders
  • Multithreaded Uploader
  • Memory fragmentation?
  • C# correct exception handling
  • "Could not open macro storage" when accessing using file on another machine
  • How to access other directories of hosted server
  • C# Jagged Array check if value exists/true
  • Why can't I type Clone() properly?
  • exception on accessing dictionary from list
  • Getting the immediate response from server without waiting to 200 message
  • Why am I getting exception Directory Is Not empty?
  • Could not load file or assembly 'CefSharp.dll' or one of its dependencies
  • Sending Email By Using C# in unity3D?
  • Correct usage of await async in webapi
  • Program update code issue
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org