How do I convert a List(Of T) to an ObservableCollection(Of T) in VB.NET? - vb.net

Is there a way to do this without iterating through the List and adding the items to the ObservableCollection?

No, there is no way to directly convert the list to an observable collection. You must add each item to the collection. However, below is a shortcut to allow the framework to enumerate the values and add them for you.
Dim list as new List(of string)
...some stuff to fill the list...
Dim observable as new ObservableCollection(of string)(list)

I'm late but I want to share this interesting piece for converting a list into a ObservableCollection if you need a loop:
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> coll)
{
var c = new ObservableCollection<T>();
foreach (var e in coll) c.Add(e);
return c;
}
You could pass an collection to the ObservableCollection constructor:
List<Product> myProds = ......
ObservableCollection<Product> oc = new ObservableCollection<Product>(myProds);
Now you have to translate these to VB.NET :)

//Create an observable collection TObservable.
ObservableCollection (TObservable) =new ObservableCollection (TObservable)();
//Convert List items(OldListItems) to collection
OldListItems.ForEach(x => TObservable.Add(x));

to clarify what Junior is saying (with an added example if you're using LINQ that returns an IEnumerable):
//Applications is an Observable Collection of Application in this example
List<Application> filteredApplications =
(Applications.Where( i => i.someBooleanDetail )).ToList();
Applications = new ObservableCollection<Application>( filteredApplications );

Even though I'm late, I wanna share a quick enhancement to Junior's answer: let the developer define the converter function used to convert observable collection objects from the source collection to the destination one.
Like the following:
public static ObservableCollection<TDest> ToObservableCollection<TDest, TSource>(this IEnumerable<TSource> coll, Func<TSource, TDest> converter)
{
var c = new ObservableCollection<TDest>();
foreach (var e in coll)
{
c.Add(converter(e));
}
return c;
}

ObservableCollection<yourobjectname> result = new ObservableCollection<yourobjectname>(yourobjectlist);

Related

ViewModel as source type for new object with Automapper?

Is it possible to use an ViewModel object (ViewModels.Combined) that holds two Lists (domains and reginfos) as a source type for Automapper?
Sample source code:
public ActionResult Index()
{
var domains = from x in unitofwork.DomainRepository.Get()
select x;
var reginfos = from x in unitofwork.RegInfoRepository.Get()
select x;
var combined = new Combined(domains, reginfos);
Mapper.CreateMap<Combined, Home>();
Home[] something = Mapper.Map<Combined[], Home[]>(combined); // throws error
return View();
}
The ideal situation would be to flatten ViewModels.Combined and be able to use ex. Model.domains.FullName.
Thanks in advance and sorry for mixing up term. I'm pretty new to mvc and .net

NHibernate CreateSqlQuery() result to an ObservableCollection

I've the following:
using (ISession session = Config.SessionFactory.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
// This is a System.Collections.ArrayList,contains all my records returned from the session
var list = session.CreateSQLQuery(selectQuery).List();
// I want to put these records in an ObservableCollection of a specific Type
// Something like htis:
MyCollection = new ObservableCollection<MyType>(list);
}
}
This is not working and casting isn't an option here. Is there any way to put my retrurned list to the ObservableCollection?
I've got my ObservableCollection filled by using the following:
var query = session.CreateSQLQuery(selectQuery).AddEntity(typeof(MyType));
myObservableCollection = new ObservableCollection<MyType>(query.List<MyType>());
The List() returns ArrayList. Each value in ArrayList has some value which is type of object.
It can not be converted into directly any specific class. so create a mapping file then only you can get list of your required object.

How to add one more properties in current class at runtime using C#

I have some properties in my viewmodel. At runtime I need to add one more property into that viewmodel.
For example:
var avm= new AnalysisViewModel();
foreach (var grades in gradeList)
{
avm = new AnalysisViewModel
{
InfractionAverage = searchResult.Where(x=>x.GradeId == grades),
//Here i want to add one move property and want to assign value for my list.
};
}
Please guide me how to achieve this requirement
Hmm try with PropertyBuilder. http://msdn.microsoft.com/en-us/library/system.reflection.emit.propertybuilder.aspx

Using the return type IQueryable<TABLE_1>

I am new to silverlight, many posts indicate using observablecollection is the best.
Domainservice1 returns IQUERYABLE type.
How to work with this return type in
silverlight side?
How to convert/cast the data returned
to observable collection?
The DomainServices1.cs
public IQueryable<TABLE_1> GetTABLE_1()
{
return this.ObjectContext.TABLE_1;
}
*The HOME.XAML.CS***
public Home()
{
InitializeComponent();
this.Title = ApplicationStrings.HomePageTitle;
Web.DomainService1 dservice = new Web.DomainService1();
EntityQuery<Web.TABLE_1> query=new EntityQuery<Web.TABLE_1>();
query = dservice.GetTABLE_1Query();
//Convert result to ObservableCollection
//bind the grid ITEM SOURCE
}
The IQueryable does not return results until you enumerate the collection. so for instance if you wanted to limit the results of that dservice.getTable_1Query with a .where() you could...
to get the object into an observable collection you .tolist the query like this
observablecollection<Table1> t=new observablecollection<Table1>(query.ToList());
I actually think there is a little more that you have to do(a loadoperation is how I do mine)
I am in the learning stages of the linq dynamic, but from other applications that i have had to convert returned results to an observable collection; that is how i did it. I actually wrote an exension so that I could .ToObservableCollection

Lambda and VB.NET

I have found this example on StackOverflow:
var people = new List<Person> {
new Person{Name="aaa", Salary=15000, isHip=false}
,new Person{Name="aaa", Salary=15000, isHip=false}
,new Person{Name="bbb", Salary=20000, isHip=false}
,new Person{Name="ccc", Salary=25000, isHip=false}
,new Person{Name="ddd", Salary=30000, isHip=false}
,new Person{Name="eee", Salary=35000, isHip=false}
};
people.Where(p => p.Salary < 25000).Update(p => p.isHip = true);
foreach (var p in people)
{
Console.WriteLine("{0} - {1}", p.Name, p.isHip);
}
public static void Update<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
action(item);
}
In C# everything works fine.
I tried to convert it in VB.NET.
Here's the code:
<System.Runtime.CompilerServices.Extension()> _
Public Sub Update(Of T)(ByVal source As IEnumerable(Of T), ByVal action As Action(Of T))
For Each item In source
action(item)
Next item
End Sub
If I try to update my collection things don't work, though:
people.Where(Function(p) p.Salary < 25000).Update(Function(p) p.isHip = true)
I am using VS2008 (3.5)
This thing is driving me crazy.
Is there anybody who can help me?
Alberto
You should always post what exactly is not working.
In your case, you want to Update list elements, which works though passing an Action(Of T) that should be run for every element.
Such an action, that is just run, performs some side-effects but returns no value is described by exactly one VB construct: A Sub.
Thus what you would want to write is
.Update(Sub(p) p.isHip = true)
which is valid VB2010, but simply does not work in the 2008 version. C# doesn't have a problem there, but in your VB code, you want to pass a Function which has to produce a value and not just perform an assignment. Func(Of ...) would be the appropriate type of that expression.
So what to do?
You can't just express what you want in the syntax of your version. But probably you shouldn't - build a new collection without modifying an old one. Is soon as you're dealing with value types/properties, the above approch won't work at all, since actually a temporary collection returned by Where is modified. Linq is no modification language, but a query system.
Anyway: Just use a plain loop.