I have a MVC that posts an array of int, and I want to convert that array of int's to IEnumerable<MyTestObj>, how is that done? I cant use myintArr.AsEnumerable()
it seems.
views:
88answers:
4You need something along the lines of the following (depending how you create the object):
myIntArr.Select(i => new MyTestObj(i));
// or...
myIntArr.Select(i => (MyTestObj)i);
// or...
myIntArr.Select(i => new MyTestObj { SomeProperty = i });
you did not clarify exactly what T
you need ... but here's a try:
IEnumerable<MyTestObj> dataStore = /* my magic dataStore */;
IEnumerable<int> arrayOfIds = /* my magic array of ids */;
IEnumerable<MyTestObj> objects = dataStore.Where(element => arrayOfIds.Contains(element.Id));
this is not really efficient! you should rather go for a dictionary, like:
IDictionary<int, MyTestObj> dataStore = /* my magic dataStore */;
IEnumerable<int> arrayOfIds = /* my magic array of ids */;
IEnumerable<MyTestObj> objects = from id in arrayOfIds
where dataStore.ContainsKey(id)
select dataStore[id];
if you just need IEnumerable<int>
, you don't need to do anything at all, cause int[]
is already IEnumerable<int>
I'm a little confused. I am assuming that you have something like this for an action:
public ActionResult MyAction(int [] postedValues)
If that's the case then postedValues
would already be IEnumerable. Not sure what problem you are having. It this isn't what you were asking then look at wither Mehrdad's or Andreas's answers.
I may be missing the point here, but doesn't an array support IEnumerable? In other words just use your array as it is (assuming you want an enumerable of int).
If you want an enumerable collection of some other object I think the other answers address that, but it's not clear (to me at least) what it is you are trying to acheive.