return list from linq function - linq

I want to return list of typenames from the class ApplicaitonType but i recieve error
Error 1 Instance argument: cannot convert from 'System.Linq.IQueryable' to 'System.Collections.Generic.IEnumerable' C:\Users\sharaman\documents\visual studio 2010\Projects\IssueTracking\BAL_IssueTracking\AppQuery.cs 19 17 BAL_IssueTracking
Please provide your feed back on it...much appericated
public static List AppType()
{
List<ApplicationType> m = new List<ApplicationType>();
var context = new Dll_IssueTracking.IssuTrackingEntities();// Object context defined in Dll_IssuTracking DLL
var query = from c in context.ApplicationTypes//Query to find TypeNames
select new { c.TypeName };
//return query.ToList<ApplicationType>();
m = query.ToList<ApplicationType>();//Error here
return m;
}

Your query selects a sequence of an anonymous type:
select new { c.TypeName };
It's not clear how you're expecting to turn that anonymous type into an ApplicationType.
Given your data source name, I'd expect the method to be as simple as:
public static List<ApplicationType> AppType()
{
using (var context = new Dll_IssueTracking.IssuTrackingEntities())
{
return context.ApplicationTypes.ToList();
}
}
In particular, it's pointless to create an instance of List<ApplicationType> and then ignore it, as you currently do:
List<ApplicationType> m = new List<ApplicationType>();
...
m = query.ToList<ApplicationType>();
return m;
Why would you bother with the variable here, and why would you assign a value to it which you never use?
EDIT: From your comment:
Actually I need to return TypeNames from ApplicaitonType class and bind to Dropdownlist through this function
That suggests your method is declared inappropriately. Either you can return a List<ApplicationType> and specify TypeName as the display part in the data binding, or you can change your method to return a List<string> (assuming that's the type of TypeName):
public static List<string> GetApplicationTypeNames()
{
using (var context = new Dll_IssueTracking.IssuTrackingEntities())
{
return context.ApplicationTypes.Select(type => type.typeName)
.ToList();
}
}

try with this code
public static List<ApplicationType> AppType()
{
var context = new Dll_IssueTracking.IssuTrackingEntities();// Object context defined in Dll_IssuTracking DLL
var query = from c in context.ApplicationTypes//Query to find TypeNames
select new ApplicationType{TypeName = c.TypeName };
return query.ToList();
}

Related

How to select multiple class properties in LINQ Expression?

If I have a class like this
`
class Person
{
public string First;
public string Last;
public bool IsMarried;
public int Age;
}`
Then how can I write a LINQ Expression where I could select properties of a Person. I want to do something like this (user can enter 1..n properties)
SelectData<Person>(x=>x.First, x.Last,x.Age);
What would be the input expression of my SelectData function ?
SelectData(Expression<Func<TEntity, List<string>>> selector); ?
EDIT
In my SelectData function I want to extract property names and then generate SELECT clause of my SQL Query dynamically.
SOLUTION
Ok, so what I have done is to have my SelectData as
public IEnumerable<TEntity> SelectData(Expression<Func<TEntity, object>> expression)
{
NewExpression body = (NewExpression)expression.Body;
List<string> columns = new List<string>();
foreach(var arg in body.Arguments)
{
var exp = (MemberExpression)arg;
columns.Add(exp.Member.Name);
}
//build query
And to use it I call it like this
ccc<Person>().SelectData(x => new { x.First, x.Last, x.Age });
Hopefully it would help someone who is looking :)
Thanks,
IY
I think it would be better to use delegates instead of Reflection. Apart from the fact that delegates will be faster, the compiler will complain if you try to fetch property values that do not exist. With reflection you won't find errors until run time.
Luckily there is already something like that. it is implemented as an extension function of IEnumerable, and it is called Select (irony intended)
I think you want something like this:
I have a sequence of Persons, and I want you to create a Linq
statement that returns per Person a new object that contains the
properties First and Last.
Or:
I have a sequence of Persns and I want you to create a Linq statement
that returns per Person a new object that contains Age, IsMarried,
whether it is an adult and to make it difficult: one Property called
Name which is a combination of First and Last
The function SelectData would be something like this:
IEnumerable<TResult> SelectData<TSource, TResult>(this IEnumerable<TSource> source,
Func<TSource, TResult> selector)
{
return source.Select(selector);
}
Usage:
problem 1: return per Person a new object that contains the
properties First and Last.
var result = Persons.SelectData(person => new
{
First = person.First,
Last = person.Last,
});
problem 2: return per Person a new object that contains Age, IsMarried, whether he is an adult and one Property called Name which is a combination
of First and Last
var result = Persons.SelectData(person => new
{
Age = person.Name,
IsMarried = person.IsMarried,
IsAdult = person.Age > 21,
Name = new
{
First = person.First,
Last = person.Last,
},
});
Well let's face it, your SelectData is nothing more than Enumerable.Select
You could of course create a function where you'd let the caller provide a list of properties he wants, but (1) that would limit his possibilities to design the end result and (2) it would be way more typing for him to call the function.
Instead of:
.Select(p => new
{
P1 = p.Property1,
P2 = p.Property2,
}
he would have to type something like
.SelectData(new List<Func<TSource, TResult>()
{
p => p.Property1, // first element of the property list
p -> p.Property2, // second element of the property list
}
You won't be able to name the returned properties, you won't be able to combine several properties into one:
.Select(p => p.First + p.Last)
And what would you gain by it?
Highly discouraged requirement!
You could achive similar result using Reflection and Extension Method
Model:
namespace ConsoleApplication2
{
class Person
{
public string First { get; set; }
public string Last { get; set; }
public bool IsMarried { get; set; }
public int Age { get; set; }
}
}
Service:
using System.Collections.Generic;
using System.Linq;
namespace Test
{
public static class Service
{
public static IQueryable<IQueryable<KeyValuePair<string, object>>> SelectData<T>(this IQueryable<T> queryable, string[] properties)
{
var queryResult = new List<IQueryable<KeyValuePair<string, object>>>();
foreach (T entity in queryable)
{
var entityProperties = new List<KeyValuePair<string, object>>();
foreach (string property in properties)
{
var value = typeof(T).GetProperty(property).GetValue(entity);
var entityProperty = new KeyValuePair<string, object>(property, value);
entityProperties.Add(entityProperty);
}
queryResult.Add(entityProperties.AsQueryable());
}
return queryResult.AsQueryable();
}
}
}
Usage:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var list = new List<Person>()
{
new Person()
{
Age = 18,
First = "test1",
IsMarried = false,
Last = "test2"
},
new Person()
{
Age = 40,
First = "test3",
IsMarried = true,
Last = "test4"
}
};
var queryableList = list.AsQueryable();
string[] properties = { "Age", "Last" };
var result = queryableList.SelectData(properties);
foreach (var element in result)
{
foreach (var property in element)
{
Console.WriteLine($"{property.Key}: {property.Value}");
}
}
Console.ReadKey();
}
}
}
Result:
Age: 18
Last: test2
Age: 40
Last: test4

Use common linq expression to avoid duplicate of entity to poco

How may I avoid to duplicate the code I use for mapping a database entity to a poco object?
Given this code:
private IQueryable<DummyExtended> Find()
{
return (from dt in Entities.dummy_table
select new DummyExtended
{
Description = dt.table_1.table_2.description,
Dummy = new Dummy
{
Name = d.name,
Notes = d.notes,
HelpText = d.help_text
}
}).AsQueryable();
}
Can I create a common linq expression to be re-used for both methods?
private IQueryable<DummyExtended> Find()
{
return (from dt in Entities.dummy_table
select new DummyExtended
{
Description = dt.table_1.table_2.description,
Dummy = ...???
}).AsQueryable();
}
private IQueryable<DummyAlsoExtended> FindAnother()
{
return (from dt in Entities.dummy_table
select new DummyAlsoExtended
{
InnerHtml = dt.table_html.description,
Dummy = ....??
}).AsQueryable();
}
Example:
public static Expression<Func<dummy_table, Dummy>> EntityToPoco()
{
return d => new Dummy
{
Name = d.name,
Notes = d.notes,
HelpText = d.help_text
};
}
I can't quite get it right
....
Dummy = ExtensionClass.EntityToPoco()
So you have a dummy_table which is a Enumerable or Queryable sequence of objects. Let's assume that the sequence contains objects of class DummyTableElement.
You showed, that if you have a DummyTableElement you know how to convert it into a Dummy object. You want to reuse this function to create other objects like DummyExtended and DummyAlsoExtended. If you want to do this LINQ-alike, it is best to create extension functions for it:
static class DummyTableElementExtensions
{
public static Dummy ToDummy(this TableElement tableElement)
{
return new Dummy()
{
Name = tableElement.name,
Notes = tableElement.notes,
HelpText = tableElement.help_text
};
}
}
Once you have this, you can create similar functions to convert TableElements into DummyExtended and DummyAlsoExtended. They will be one-liners.
In the same extension class:
public static DummyExtended ToDummyExtended(this TableElement tableElement)
{
return new DummyExtended()
{
Description = tableElement.table_1.table_2.description,
Dummy = tableElement.ToDummy(),
};
}
public static DummyAlsoExtended ToDummyAlsoExtended(this TableElement tableElement)
{
return new DummyAlsoExtended
{
InnerHtml = tableElement.table_html.description,
Dummy = tableElement.ToDummy(),
};
}
And once you've got these, you can create extension functions to convert any IQueryable of TableElements:
public static IQueryable<DummyExtended> ToDummyExtended(
this IQueryable<TableElement> tableElements)
{
return tableElements
.Select(tableElement => tableelement.ToDummyExtended();
}
And a similar one-line function for DummyAlsoExtended.
Your Find function and FindAnother function will also be one-liners:
private IQueryable<DummyExtended> Find()
{
return dummy_table.ToDummyExtended();
}
private IQueryable<DummyAlsoExtended> FindAnother()
{
return dummy_table.ToDummyAlsoExtended();
}
I'm not sure why you wanted to use an expression in this. It doesn't seem that DummyExtended and DummyAlsoExtended are really similar, except that they both have a property Dummy.
One reason to parameterize the destination of your find function could be because you want to create anonymous classes in your Find function.
Again, once you've created ToDummy this will be a one-liner:
public static IQueryable<TResult> Find<TSource, TResult>(
this IQueryable<TSource> source,
Expression<Func<TSource, TResult>> resultSelector)
{
return source.Select(sourceElement => resultSelector(sourceElement);
}
Usage would be:
var X = dummy_Table.find(tableElement => new
{
foo = tableElement.CalculateFoo(),
bar = tableElement.CalculateBar(),
Dummy = tableElement.ToDummy(),
});

Linq to entity - dynamic query

public void ApproveRowTable(string tablename, List<int> idValues)
{
foreach (var x in idValues)
{
var context = new SSPModel.sspEntities();
var genRules = (from a in context.GeneralRules
where a.ID == x
select a).SingleOrDefault();
genRules.Approved_by = GlobalClass.GlobalVar;
genRules.Approved_on = DateTime.Now;
context.SaveChanges();
}
}
In my query (from a in context.GeneralRules...) I would like to make it query base on a parameter (tablename) rather than i have to go and supply the name of the table in the query (as it is doing right now.). Any way i can get it to do that .. basic.. from a in context.TABLENAME -- TABLENAME is a parameter that is going to be passed when the function is called. Help
This will be difficult if your entity types do not all implement the same interface or derive from the same class. If they do, it's pretty simple:
// example base type, which your entities would need to implement
public interface IApprovable
{
public int ID {get; set;}
public string Approved_by {get; set;}
public DateTime Approved_on {get; set;}
}
//...
public void ApproveRowTable<T>(List<int> idValues)
where T : IApprovable
{
using(var context = new SSPModel.sspEntities())
{
var table = context.Set<T>();
var entities = table.Where(e => idValues.Contains(e.ID));
foreach(var entity in entities)
{
entity.Approved_by = GlobalClass.GlobalVar;
entity.Approved_on = DateTime.Now;
}
context.SaveChanges();
}
}
If your entity types do not implement a common base type, then you should modify them by creating empty partials which do implement it:
public partial class GeneralRule : IApprovable {}
If you cannot do that, then you can do something like the following. (I'm assuming ID is the PK, so we can use Find() rather than needing to build an expression:
public void ApproveTableRows(Type entityType, IEnumerable<int> idsToApprove)
{
using(var context = new SSPModel.sspEntities())
{
var set = context.Set(entityType);
if(set == null)
throw new ArgumentException("No DbSet found with provided name", "tableSetName");
var approveByProperty = entityType.GetProperty("Approved_by");
var approveOnProperty = entityType.GetProperty("Approved_on");
if(approveByProperty == null || approveOnProperty == null)
throw new InvalidOperationException("Entity type does not contain approval properties");
foreach (object id in idsToApprove)
{
var entityInstance = set.Find(id);
approveByProperty.SetValue(entityInstance, GlobalClass.GlobalVar);
approveOnProperty.SetValue(entityInstance, DateTime.Now);
}
context.SaveChanges();
}
}
As you can see, this is less efficient, as it issues a new query for each ID rather than getting them all at once. Also, the method accepts an entity Type rather than a string, to avoid the need to hunt down the right property by reflection. This could be improved, but really I think you should probably update your entities to implement a shared interface.
I assume you would like to have the method generic. When you are using EF all your tables are represented as objects, so you don't have to specify which table you want by name, just use a generic parameter.
I doubt that my solution is best, but it should work. But I have to warn you, reflection is slow and many times its usage is not right.
public void ApproveRowTable<T>(List<int> idValues)
{
var context = new SSPModel.sspEntities();
var table = context.GetType().GetProperties().OfType<T>().Single();
var genRules = (from a in table
where a.ID == x
select a).SingleOrDefault();
genRules.Approved_by = GlobalClass.GlobalVar;
genRules.Approved_on = DateTime.Now;
context.SaveChanges();
}

Make a new generic list from a list within a list in Linq with lambda expressions?

Okay so I have a POCO class that may contain another POCO class as an array. In some instances when I get the data I want to CREATE a list of the lists but not as a level down but all on the same level. I think I am missing something very simple so I thought I would ask here. I keep trying different syntax for Lambdas but the data is there, I can just never make it appear near the top. I would like the solution to be in lambdas if possible instead of doing the old school foreach. I was not sure if you can do this inline at all or if you have to declare a collection first and then add to it. Where I am at:
class Program
{
public class lowerlevel
{
public string ChildName;
}
public class upperlevel
{
public string ItemName;
public lowerlevel[] ChildNames;
}
static void Main(string[] args)
{
// Create a list of a POCO object that has lists in it as well.
List<upperlevel> items = new List<upperlevel>
{
// declaration of top level item
new upperlevel
{
ItemName = "FirstItem",
// declaration of children
ChildNames = new lowerlevel[]
{new lowerlevel {ChildName = "Part1"}, new lowerlevel {ChildName = "Part2"}},
},
// declaration of top level item
new upperlevel
{
ItemName = "SecondItem",
// declaration of children
ChildNames = new lowerlevel[] { new lowerlevel { ChildName = "Part3" } }
}
};
var stuff = items.Select(l1 => l1.ChildNames.ToList().Select(l2 =>
new lowerlevel
{
ChildName = l2.ChildName
}))
.ToList();
// Arghh! I just want to make a new list with lambdas that is NOT nested a level down! This is NOT what I want but it is valid.
stuff.ForEach(n => n.ToList().ForEach(n2 => n2.ChildName));
// I want this but it does not work as I am not doing the expression right
// stuff.Foreach(n => n.ChildName);
}
}
Try using a SelectMany() Rather than .Select()
var stuff = items.SelectMany...

Cast ActionScript Object to Model

Is there any "automatic way" to casts an "Object" to a personalized Model Data Type in ActionScript 3?
Example:
package Example{
public class ExampleModel{
private _id:int;
private _randomAttribute:String;
public function ExampleModel(){
_id = 0;
_randomAttribute = "";
}
public function get id():int{
return _id;
}
public function set id(value:int):void{
_id = value;
}
public function get randomAttribute():String{
return _randomAttribute;
}
public function set randomAttribute(value:String):void{
_randomAttribute = value;
}
}
}
Then, in some part of my code, lets assume that I have something like this:
var _obj:Object = new Object();
_obj.id = 1;
obj.randomAttribute = "Hello World";
What I want would be something like:
var _exampleModel:ExampleModel = obj as ExampleModel;
But when I do this, the result on _exampleModel is null.
Any ideas?
Thanks.
EDIT:
According to Manish's answer, all I changed was the type of p var, which allows me to go through every kind of attribute:
public function fromObject(obj:Object):void{
//p:* includes every type of attributes.
for (var p:* in obj)
if (this.hasOwnProperty(p))
// Set private var directly.
this["_" + p] = obj[p];
}
Thanks Manish and rcdmk.
Manish's answer was enough for me and according to rcdmk's comment, the p:String isn't about the Type of data that the loop will go through, it is actually the name of the property, which makes sense because every name is a String.
The only way to automatically "cast" it is the following:
var model:Model = new Model();
var obj:Object = { id: "98123", name: "John Doe" };
for (var p:String in obj) {
if (model.hasOwnProperty(p))
model[p] = obj[p];
}
(Note: Model.id and Model.name are both type String in my example.)
A more proper way to do it, of course, is to pass the plain object to the Model object and let the Model object absorb it.
var model:Model = new Model(obj);
Or:
var model:Model = new Model();
model.fromObject(obj);
Where in the Model code you have:
public function Model(obj:Object = null)
{
if (obj != null)
fromObject(obj);
}
public function fromObject(obj:Object):void
{
for (var p:String in obj)
if (this.hasOwnProperty(p))
// Set private var directly.
this["_" + p] = obj[p];
}
This code can be in your abstract base Model class, and all your specific Model subclasses (e.g. ProductModel, CustomerModel, etc.) can use it automatically.
e.g.
public class ProductModel extends Model
{
public function ProductModel(obj:Object = null)
{
super(obj);
}
}

Resources