It is easy ignoring null values in the source, but then the destination will have the default value. Instead, I want the destination to keep its original value. This seems to do the job:
public static Action<IMemberConfigurationExpression<TSource, TDestination, object>> IgnoreNullInSource<TSource, TDestination>()
{
return x =>
{
x.Condition((s, d, sm) =>
{
return sm != null;
});
x.UseDestinationValue();
};
}
CreateMap<MySourceType, MyDestinationType>()
.ForAllMembers(IgnoreNullInSource<MySourceType, MyDestinationType>());
It is reusable, but I don't like repeating the generic types. Plus I feel like I am overcomplicating things. Is there a better or even build in way, with converters maybe? I did not find a way to use a converter (or memberconverter) with .ForAllMembers().
Related
Is possible in groovy to remove a object from list through the object?
I know how to remove from the list, but can I remove it from the list with only know the reference of the certain object. (I don't want a null object in the list)
Probably it is not possible, but Groovy have surprises.
class Foo() {
List<Boo> boos
}
class BoosHandler {
void doSomethingWithBoo() {
boos.each {
analyse(it)
}
}
void analyse(Boo boo) {
if(boo.something == "wrong") {
remove(boo) // Pseudo style for removing object boo from the list (Foo.boos)
}
}
}
No, not possible.
I would also not do this, as in a multi-threaded environment it would be unpredictable...
You're better (as you probably know) doing:
List<Boo> filter(String notThis) {
boos.findAll { it.something != notThis }
}
ie: return a new list, and don't change the original
Im wondering if its possible to reuse my overload of the Sort(Comparison) method to sort both labels and textboxes by tabIndex. Ive already tried and i couldnt get it to work. Any help would be appreciated.
foreach(Control control in gbUserInputs.Controls)
{
if (control is Label)
{
inputLabels.Add((Label)control);
}
if (control is TextBox)
{
inputTxtboxes.Add((TextBox)control);
}
}
Sort method call(this doesnt work).
inputLabels.Sort(sortMyInputs<Label>);
Overload of sort method.
private static int sortMyInputs<T>(T entry1, T entry2)
{
return entry1.TabIndex.CompareTo(entry2.TabIndex);
}
You shouldn't be making a generic method:
private static int CompareLabels(Label entry1, Label entry2)
{
return entry1.TabIndex.CompareTo(entry2.TabIndex);
}
The point of a generic delegate is to allow it to hold methods of different concrete types; not to allow it to hold methods that are themselves generic.
If you want to reuse your method, you can modify it to take Control (which both TextBox and Label inherit); you would still be able to pass it to List<Label>.Sort because of delegate covariance.
If you're using .Net < 4, which doesn't have delegate covariance, you can do it your way by adding a constraint to the method so that it knows what T can be:
private static int CompareLabels<T>(T entry1, T entry2) where T : Control
{
return entry1.TabIndex.CompareTo(entry2.TabIndex);
}
You can also simply replace all of your code with one line of LINQ:
inputLabels = gbUserInputs.Controls.OfType<Label>()
.OrderBy(c => c.TabIndex)
.ToList();
I need to validate a field's value according to two different validation rules:
An object of my own which contains a regex and a range (for string it's length range).
A list of possible values.
So I can do this:
public static bool Validate(string fieldValue, string fieldType, ValidationParameters validationParameters)
{
...
}
public static bool Validate(string fieldValue, string fieldType, string[] possibleValues)
{
...
}
But that requires the user to ungracefully if.
I can also do this:
public static bool Validate(string fieldValue, string fieldType, ValidationParameters validationParameters=null,string[] possibleValues=null)
{
...
}
Now the user can just send he's data, without redundant if, But I can't make sure validationParameters or possibleValues (one of them) got a value.
Is there a third option, one in which the user won't have to check which method he uses, but I won't have to worry that he doesn't send any of the two fields (in code, not documentation)?
If not, which way of the two above is better (less error-prone and more elegant)?
Thanks.
I personally would do two overloaded methods. The main reasoning for this is:
But I can't make sure validationParameters or possibleValues (one of them) got a value.
Optional arguments, in my opinion, should be exactly that: optional. Making two optional arguments where one is required seems like a problematic design choice.
Your main reasoning for avoiding this seems to be:
But that requires the user to ungracefully if.
However, I don't see the problem. The user is going to have to construct either the string collection (which, I personally, would either make IEnumerable<string> instead of string[], or do params string[] possibleValues) or the ValidationParameters. If they already need to construct the arguments to pass, adding an if conditional seems unnecessary (each path could just call the validation).
If they are validating by different concepts, they should probably be named differently. Say, ValidateByValidationParameters and ValidateByPossibleValues. Now the question is, why wouldn't you want the caller to carefully select which one he is using?
Because you can't require that one of them is sent, I'd recommend the former option, but I don't understand what you mean by the fact that you don't like that the user has to "ungracefully if".
You can overload the methods - as you said - or do something like this:
enum TYPE { VAL_1, VAL_2 }
void function(TYPE validateType, object o)
{
swich(validateType)
{
case VAL_1:
List<string> par = o List<String>;
if(par != null)
{
//...
}
break;
case VAL_2:
List<MyObject> par = o as List<MyObject>;
if(par != null)
{
//...
}
break;
}
}
Maybe it's not very typesafe, but somteimes useful.
At last - you can prepare single delegate method for every validation case and call those methods (single or many) in one place.
I have a function that returns objects of different types based on the parameter passed to this function.
Is it possible to add these different object types to a collection based on some identifier in C# 4.0?
Usually we do something like this
List or List
but i want one collection which can add object of any type.
Instead of just making a List<object> like other posters are recommending, you may want to define an interface eg IListableObject that contains a few methods that your objects need to implement. This will make any code using these objects much easier to write and will guard against unwanted objects getting into the collection down the line.
Yes, it is called object. Eg:
var objlist = new List<object>();
objlist.Add(1);
objlist.Add(true);
objlist.Add("hello");
You could use object[], List<object>, ArrayList, IEnumerable, ... but if those types have a common base type it would be better to stick to a strongly typed collection.
Really your collection should be as specific as you can make it. When you say
objects of different types
Do these objects have anything in common? Do they implement a common interface?
If so you you can specialise the list on that interface List<IMyInterface>
Otherwise List<object> will do what you want.
Update
No, not really.
I'm sorry but I'm going to question your design.
If you have a collection of different objects, how do you decide how to use one of the objects?
You're going to have a large switch statement switching on the type of the object, then you cast to a specific object and use it.
You also have have a similar switch statement in your factory method that creates the object.
One of the benefits of Object Orientation is that if you design your objects correctly then you don't need to do these large "If it's this object do this.Method(), if it's that object do that.OtherMethod()".
Can I ask, why are you putting different objects into the same collection? What's the benefit to you?
If you want a collection which can add objects of any type then List<object> is the most appropriate type.
Collections in earlier versions of C# (not generics) can contain any kind of objects. If they're value type, they will be boxed into object.
When you need to use them, you can just cast it to the original type.
You may use List<Type> to hold the type information, if that's what you want. And Type[], Hashtable, etc. are also fine. You can use typeof operator to get the type or use Object.GetType().
Also check out Dynamic type.
http://msdn.microsoft.com/en-us/library/dd264736.aspx
It will basically do the same thing.
My Suggestion:
public class ParamValue
{
object value = null;
public ParamValue(object val)
{
value = val;
}
public string AsString()
{
return value.ToString();
}
public int AsInt()
{
return int.Parse(value.ToString());
}
public int? AsNullableInt()
{
int n;
if (int.TryParse(value.ToString(), out n))
{
return n;
}
return null;
}
public bool AsBool()
{
return bool.Parse(value.ToString());
}
public bool? AsNullableBool()
{
bool b;
if (bool.TryParse(value.ToString(), out b))
{
return b;
}
return null;
}
}
public class Params
{
Dictionary<string, object> paramCol = new Dictionary<string, object>();
public void Add(string paramName, object value)
{
paramCol.Add(paramName, value);
}
public ParamValue this[string paramName]
{
get
{
object v;
if (paramCol.TryGetValue(paramName, out v))
{
return new ParamValue(v);
}
return null;
}
}
}
Use param class as a collectio to your values, you can convert the return to every type you want.
You could use a Tuple of Genric Types
public Tuple<T, T> MySuperMethod()
{
int number = 1;
string text = "Batman";
return new Tuple<int, string>(number, text);
}
The .NET Framework directly supports tuples with one to seven
elements. In addition, you can create tuples of eight or more elements
by nesting tuple objects in the Rest property of a Tuple object.
https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.100).aspx
I have a table which maps String->Integer.
Rather than create an enum statically, I want to populate the enum with values from a database. Is this possible ?
So, rather than delcaring this statically:
public enum Size { SMALL(0), MEDIUM(1), LARGE(2), SUPERSIZE(3) };
I want to create this enum dynamically since the numbers {0,1,2,3} are basically random (because they are autogenerated by the database's AUTOINCREMENT column).
No. Enums are always fixed at compile-time. The only way you could do this would be to dyamically generate the relevant bytecode.
Having said that, you should probably work out which aspects of an enum you're actually interested in. Presumably you weren't wanting to use a switch statement over them, as that would mean static code and you don't know the values statically... likewise any other references in the code.
If you really just want a map from String to Integer, you can just use a Map<String, Integer> which you populate at execution time, and you're done. If you want the EnumSet features, they would be somewhat trickier to reproduce with the same efficiency, but it may be feasible with some effort.
So, before going any further in terms of thinking about implementation, I suggest you work out what your real requirements are.
(EDIT: I've been assuming that this enum is fully dynamic, i.e. that you don't know the names or even how many values there are. If the set of names is fixed and you only need to fetch the ID from the database, that's a very different matter - see Andreas' answer.)
This is a bit tricky, since the population of those values happens at class-load time. So you will need a static access to a database connection.
As much as I value his answers, I think Jon Skeet may be wrong this time.
Take a look at this:
public enum DbEnum {
FIRST(getFromDb("FIRST")), SECOND(getFromDb("second"));
private static int getFromDb(String s) {
PreparedStatement statement = null;
ResultSet rs = null;
try {
Connection c = ConnectionFactory.getInstance().getConnection();
statement = c.prepareStatement("select id from Test where name=?");
statement.setString(1, s);
rs = statement.executeQuery();
return rs.getInt(1);
}
catch (SQLException e) {
throw new RuntimeException("error loading enum value for "+s,e);
}
finally {
try {
rs.close();
statement.close();
} catch (SQLException e) {
//ignore
}
}
throw new IllegalStateException("have no database");
}
final int value;
DbEnum(int value) {
this.value = value;
}
}
Improving on what Andreas did, you can load the contents of the database into a map to reduce the number of database connections needed.
public enum DbEnum {
FIRST(getFromDb("FIRST")),
SECOND(getFromDb("second"));
private Map<String,Integer> map;
private static int getFromDB(String s)
{
if (map == null)
{
map = new HashMap<String,Integer>();
// Continue with database code but get everything and
// then populate the map with key-value pairs.
return map.get(s);
}
else {
return map.get(s); }
}
}
Enums are not dynamic, so the short answer is that you can't do it.
Also have a look at Stack Overflow question Dynamic enum in C#.
You need to replicate in code what is in the database (or vice-versa). See this question for some good advices.
In all the languages I know enums are static. The compiler can make some optimizations on them. Therefore the short answer is no, you can't.
The question is why you want to use an enum in this way. What do you expect?
Or in other words why not use a collection instead?