Where predicate and Expression<Func<T, bool>> - c#-4.0

I have this line of code that returns index of particular object in a IList<T>
int index = list.IndexOf(list.Where(x => x.Code == searchValue).FirstOrDefault());
and I have similar construction on many places, which searches collections on different properties. My goal is to automate this, so I can have a generic method MyClass<T>
int index = myClass.Find<T>(x=> x.Code == searchValue);
or
int index = MyClass.Find<T>(x => x.Name.ToUpper().StartsWith(searchValue.ToUpper()));
Is this possible with Lambda expressions?
Edit:
For anyone that is asking the same, here is the code that is working:
public int Find(Func<T, bool> whereClause)
{
return _list.IndexOf(_list.Where<T>(whereClause).FirstOrDefault<T>());
}

I'm not sure why you think you need to use an expression tree. Assuming list is a List<T>, you should be able to use FindIndex:
int index = list.FindIndex(x => x.Code == searchValue);
If that's not what you need, please give us more information about what the types involved are.

Related

Is there a name for a trampoline class?

I'm designing a programming language and one feature I'd like to add is a cross between a trampoline function and a class. That is, a class which takes in a literal akin to a generic class taking in a type. I'm stuck on a name for these because I haven't encountered them in a language before, is there something which already means this concept or something close? Using trampoline class is an option, but if there's something that more accurately describes this or is already in use in another language I'd prefer to go with it to cut down on the amount of jargon required in the documentation.
Pseudo-code follows to illustrate this principle in case it is not clear from the above:
class Point<const int n> {
private float[n] _value;
Point() {
for (int i = 0; i < n; i++) {
this._value[i] = 0f;
}
}
Point(Point<o> other) {
for (int i = 0; i < min(n, o); i++) {
this._value[i] = 0f;
}
}
public static float operator [index] (optional float value = null) {
if (value != null) { this._value[index] = value; }
return (this._value[index]);
}
public static Point<max(o, p)> operator + (Point<const int o> p1, Point<const int p> p2) {
Point<min(o, p)> small = (p1.n < p2.n ? p1 : p2);
Point<min(o, p)> large = (p1.n < p2.n ? p2 : p1);
Point<max(o, p)> ret = new Point<max(o, p)>(large);
for (int i = 0; i < min(o, p); i++) { ret[i] += small[i] }
return (ret);
}
}
The term you are looking for is dependent types. It means that a type cannot only have type parameters (like generics), but a type can also be parameterized with arbitrary values (the dependent type parameters). For example, you can define the signature of a function that takes a number n and returns an array of length n.
Sadly, dependent type checking in general is undecidable. This is, because you have to calculate the range of possible values of the dependent type parameters while the type checking itself is executed. To actually type check the program, you have to check whether two pieces of code produce the same range of possible values. This is known as extensional function equality and this is the part that is known to be undecidable in general.
Now, it might be true that dependent type checking becomes decidable if only compile-time constants are used as dependent type parameters. However, I am not sure about that.
In the comments below, we figured out that the part that seems to be the dependent type parameter should actually not be used for the type checking. Instead, it can be seen as an implicit parameter. It is similar to implicit parameter passing in the Scala programming language.

Using MetaProgramming to Add collectWithIndex and injectWithIndex similar to eachWithIndex

Please help with a metaprogramming configuration such that I can add collections methods called collectWithIndex and injectWithIndex that work in a similar manner to eachWithIndex but of course include the base functionality of collect and inject. The new methods would accept a two (three with maps) argument closure just like eachWithIndex. I would like to have the capability to utilize these methods across many different scripts.
Use case:
List one = [1, 2, 3]
List two = [10, 20, 30]
assert [10, 40, 90] == one.collectWithIndex { value, index ->
value * two [index]
}
Once the method is developed then how would it be made available to scripts? I suspect that a jar file would be created with special extension information and then added to the classpath.
Many thanks in advance
I'm still sure, it's not a proper SO question, but I'll give you an example, how you can enrich metaclass for your multiple scripts.
Idea is based on basescript, adding required method to List's metaClass in it's constructor. You have to implement collect logic yourself, through it's pretty easy. You can use wrapping
import org.codehaus.groovy.control.CompilerConfiguration
class WithIndexInjector extends Script {
WithIndexInjector() {
println("Adding collectWithIndex to List")
List.metaClass.collectWithIndex {
int i = 0
def result = []
for (o in delegate) // delegate is a ref holding initial list.
result << it(o, i++) // it is closure given to method
result
}
}
#Override Object run() {
return null
}
}
def configuration = new CompilerConfiguration()
configuration.scriptBaseClass = WithIndexInjector.name
new GroovyShell(configuration).evaluate('''
println(['a', 'b'].collectWithIndex { it, id -> "[$id]:$it" })
''')
// will print [[0]:a, [1]:b]
If you like to do it in more functional way, without repeating collect logic, you may use wrapping proxy closure. I expect it to be slower, but maybe it's not a deal. Just replace collectWithIndex with following implementation.
List.metaClass.collectWithIndex {
def wrappingProxyClosure = { Closure collectClosure, int startIndex = 0 ->
int i = startIndex
return {
collectClosure(it, i++) // here we keep hold on outer collectClosure and i, and use call former with one extra argument. "it" is list element, provided by default collect method.
}
}
delegate.collect(wrappingProxyClosure(it))
}
offtopic: In SO community your current question will only attract minuses, not answers.

Convert String To Nullable Integer List

I'm wanting to parse a string into a nullable int list in C#
I'm able to convert it to int list bit not a nullable one
string data = "1,2";
List<int> TagIds = data.Split(',').Select(int.Parse).ToList();
say when data will be empty i want to handle that part!
Thanks
You can use following extension method:
public static int? TryGetInt32(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}
Then it's simple:
List<int?> TagIds = data.Split(',')
.Select(s => s.TryGetInt32())
.ToList();
I use that extension method always in LINQ queries if the format can be invalid, it's better than using a local variable and int.TryParse (E. Lippert gave an example, follow link).
Apart from that it may be better to use data.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries) instead which omits empty strings in the first place.

NDepend rule to warn if objects of a given type are compared using ==

as the title says: I need a NDepend rule (CQLinq) for C#/.net code, that fires whenever instances of a given type are compared using == (reference comparison). In other words, I want to force the programmer to use .Equals.
Note that the type in question has no overloaded equality operator.
Is this possible? If so, how? :)
Thanks, cheers,
Tim
With the following code with see that for value type, == translate to the IL instruction: ceq. This kind of usage cannot be detected with NDepend.
int i = 2;
int j = 3;
Debug.Assert(i == j);
var s1 = "2";
var s2 = "3";
Debug.Assert(s1 == s2);
However for reference types we can see that a operator method named op_Equality is called.
L_001d: call bool [mscorlib]System.String::op_Equality(string, string)
Hence we just need a CQLinq query that first match all method named op_Equality, and then list all callers of these methods. This can look like:
let equalityOps = Methods.WithSimpleName("op_Equality")
from m in Application.Methods.UsingAny(equalityOps)
select new { m,
typesWhereEqualityOpCalled = m.MethodsCalled.Intersect(equalityOps).Select(m1 => m1.ParentType) }
This seems to work pretty well :)

Given a collection object, would like to assign to a local variable of specific type

I'd like to recover type information using reflection. I have
public Foo(object coll, string tValue)
{
var x = col1 as IList;
if (x != null)
x.Action();
var y = col1 as IDictionary;
if (y != null)
y.Action();
}
But would like to have
public Foo(object coll, string tValue)
{
var x = col1 as IList<TValue>;
if (x != null)
x.Action();
var y = col1 as IDictionary<int, TValue>;
if (y != null)
y.Action();
}
Is it possible to arrive at and use generic interfaces instead of the old-school non-generic collection interfaces, given only the contained class name?
Once the local variable type is established, I'd like to avoid paying the reflection and dynamic invocation penalties when looping over the collection.
Another example, maybe clearer:
var list = new Dictionary<int, MyObject>();
list.Add(100, new MyObject());
object listObject = list;
var x = listObject as IDictionary<int, dynamic>;
if (x != null)
{
foreach (var entry in x)
{
Console.WriteLine(entry.Key);
Console.WriteLine(entry.Value);
}
}
x is null...
I'm not sure if you intend to call a method on generic collection for every item in the collection or if you just want the values from the generic collection.
For your third block of code, you could continue to use the non-generic interface and use an enumerator.
var x = listObject as IDictionary;
if (x != null)
{
var en = x.GetEnumerator();
while(en.MoveNext())
{
Console.WriteLine(en.Key);
Console.WriteLine(en.Value);
}
}
If you intend to call a method without knowing the exact generic types for the generic IList or IDictionary, then you'll have to use MethodInfo.Invoke. Cache the MethodInfo outside of the loop for a small performance boost.
CreateDelegate would be faster, but you'll need to know the exact generic types. You could get around that with expression trees, but the amount of code to maintain might not be worth the performance gain. Check out MagicMethod in Jon Skeets article
Making reflection fly and exploring delegates

Resources