C# convert reflection.propertyinfo to Generic.List<> - c#

How do I go about converting a reflection.propertyinfo[] to a generic.list<>?

One of the List<T> constructors accepts an IEnumerable<T> as its argument (i.e., your PropertyInfo array):
var list = new List<PropertyInfo>( propInfoArray );

var list = yourArray.ToList();

Try using .ToList()
http://msdn.microsoft.com/en-us/library/bb342261.aspx

All of the above are correct. But it should also be mentioned that, like List<T> all .net arrays implement IList<T>.
var IList<PropertyInfo> ilist = reflection.propertyinfo;
Since I know that, almost all my functions accept IList<T> when I need a list-like collection, which I can use with traditional arrays and lists.

Use the extension method ToList() available in the System.Linq namespace:
var myProperties = propertyInfoArray.ToList();

Related

assign Ienumerable parameter to ArrayList

I am trying to pass constructor IEnumerable and assign it to Arraylist
but it gives me that error
cannot convert from 'System.Collections.IEnumerable' to 'int'
Why can you explain me
IList name;
public Class1(IEnumerable list)
{
name = new ArrayList(list)
}
One option is to use:
name = new ArrayList(list.Cast<object>().ToArray());
This is necessary since ArrayList does not have a constructor that takes a IEnumerable but it does have one that takes an ICollection (and arrays implement ICollection).
I'd also strongly suggest you use List<T> rather than ArrayList in future.
You should use linq for this
name = list.ToList()

Linq namespace and method any()

So I am using System.Linq namespace and method Any() but for some reason it's shows me an error:
ArrayList does not contain a definition for Any...
I am trying to check if an array contains any item from another array. Dont know why but cant post my code. Hope you know what the problem is.
Don't use ArrayList. Use List instead.
Becouse ArrayList doesn't implement IEnumerable<T> generic interface and extension methonds from System.Linq work only with collecions that implement interface IEnumerable<T> like List<T> for example.
ArrayList is a loosely-typed collection (see in reference source) and cannot be used with Enumerable.Any which requires a strongly-typed collection (see in reference source).
BTW, you should not use loosely-typed collections, use generic collections instead.
You shouldn't use non-generic collections.
But If you really want to do this, you can write a helper method for translating your collection to IEnumerable.
static void Main(string[] args)
{
var list = new ArrayList {3, "test", null};
var result = AsEnumerable(list).Any(x => x == null);
}
private static IEnumerable<object> ToEnumerable(ArrayList data)
{
var enumerator = data.GetEnumerator();
while (enumerator.MoveNext())
yield return enumerator.Current;
}
But It's just an example. Use List instead of ArrayList

How to remove x items from collection using LINQ?

Is there a way to remove all items except first one from any type of collection (Control.Items, List ....) using LINQ only ?
No. LINQ is designed for querying collections (no side-effects), not for adding or removing items.
What you can do is write a query that takes the first element of the collection:
var result = source.Take(1);
Note that LINQ doesn't work with all types of collections; you need a LINQ provider to make LINQ work. For instance, source must implement IEnumerable<T> to use the extension methods of the Enumerable Class (LINQ-to-Objects).
How about something using reflection?
static void RemoveButFirst(object o){
Type t = o.GetType();
System.Reflection.MethodInfo rm = t.GetMethod("RemoveAt",
new Type[]{typeof(int)});
System.Reflection.PropertyInfo count = t.GetProperty("Count");
for (int n = (int)(count.GetValue(o,null)) ; n>1; n--)
rm.Invoke(o, new object[]{n-1});
}
This would work any time your collection exposed an int Count property and a RemoveAt(int) method, which I think those collections should.
And a more concise version, using dynamic, if you work with C# 4.0:
public static void RemoveBut(dynamic col, int k){
for (int n = col.Count; n>k; n--)
col.RemoveAt(n-1);
}
You can use .Take(1), but it returns a new collection, and leaves the original intact.
The idea of LINQ came from functional programming where everything is immutable, because of that, they didn't make it possible to modify the collections with LINQ.
Jon Skeet has a comment on the subject: LINQ equivalent of foreach for IEnumerable<T>
How about (in linq):
var result = list.Where(l => l != list.First());
But this would be better:
var result = list.Take(1);
List<string> collection = new List<string>();
collection.RemoveAll(p => p.StartsWith("something"));
listXpto.Where(x=>true /* here goes your query */)
.Select(x=>{listXpto.Remove(x); return null})
But I donĀ“t know the real utility of that.
Remember that the remove method is for ILists, not IQueryable in general.

How to get an empty list of a collection?

I have a collection of anonymous class and I want to return an empty list of it.
What is the best readable expression to use?
I though of the following but I don't think they are readably enough:
var result = MyCollection.Take(0).ToList();
var result = MyCollection.Where(p => false).ToList();
Note: I don't want to empty the collection itself.
Any suggestion!
Whats about:
Enumerable.Empty<T>();
This returns an empty enumerable which is of type T. If you really want a List so you are free to do this:
Enumerable.Empty<T>().ToList<T>();
Actually, if you use a generic extension you don't even have to use any Linq to achieve this, you already have the anonymous type exposed through T
public static IList<T> GetEmptyList<T>(this IEnumerable<T> source)
{
return new List<T>();
}
var emp = MyCollection.GetEmptyList();
Given that your first suggestion works and should perform well - if readability is the only issue, why not create an extension method:
public static IList<T> CreateEmptyCopy(this IEnumerable<T> source)
{
return source.Take(0).ToList();
}
Now you can refactor your example to
var result = MyCollection.CreateEmptyCopy();
For performance reasons, you should stick with the first option you came up with.
The other one would iterate over the entire collection before returning an empty list.
Because the anonymous type there is no way, in source code, to create a list. There is, however, a way to create such list through reflection.

C#: Union of two ICollections? (equivalent of Java's addAll())

I have two ICollections of which I would like to take the union. Currently, I'm doing this with a foreach loop, but that feels verbose and hideous. What is the C# equivalent of Java's addAll()?
Example of this problem:
ICollection<IDictionary<string, string>> result = new HashSet<IDictionary<string, string>>();
// ...
ICollection<IDictionary<string, string>> fromSubTree = GetAllTypeWithin(elementName, element);
foreach( IDictionary<string, string> dict in fromSubTree ) { // hacky
result.Add(dict);
}
// result is now the union of the two sets
You can use the Enumerable.Union extension method:
result = result.Union(fromSubTree).ToList();
Since result is declared ICollection<T>, you'll need the ToList() call to convert the resulting IEnumerable<T> into a List<T> (which implements ICollection<T>). If enumeration is acceptable, you could leave the ToList() call off, and get deferred execution (if desired).
AddRange() appends the source list to the end of another, and may suit your needs.
destList.AddRange(srcList);
LINQ's Enumerable.Union will work:

Categories

Resources