Im looking for a way to gain the name of an object through the ID that it has been set to.
The first part of the name is always the same, eg. "Rating" and then I would want to concatenate it with the current value of a count integer, eg. "Rating" + i.
Is there any method to concatenate partial object names and variables to construct an object name or is it simply a case of iterating through an array?
-
3You need to provide context/an example as I don't think its clear what you have and what you want to get.Alex K.– Alex K.2014-10-20 11:43:25 +00:00Commented Oct 20, 2014 at 11:43
-
You can use Linq but at the bottom line it will iterate through the members of the list/array anyway.Amorphis– Amorphis2014-10-20 11:46:00 +00:00Commented Oct 20, 2014 at 11:46
Add a comment
|
2 Answers
Assuming the name of the object means the class name, you could do something like so:
var typeName = this.GetType().Name;
for (int i = 0; i < 5; i++)
{
Debug.WriteLine(String.Format("{0}{1}", typeName, i));
}
Naturally, you'd need to change the code to suit your needs, but for a class named Test, that would print this to the Debug output window
Test0
Test1
Test2
Test3
Test4
3 Comments
matt
this seems to be the correct method but could it be implemented alongside
<objectname>.Text or <objectname>.Value @Joeb454Joe
Do you mean when you have an instance of your class (e.g. a
Rating object), or without an instance of the object available?matt
with an instance available/created, eg. lblCounter1.Text bu accessed through ("lblCounter" + i).Text?
Generally, to project a collection of objects, you would use LINQ, or more specifically IEnumerable.Select. In this case, you are projecting an int (the Id property of type int) into a string, so the general method is:
public static IEnumerable<string> GetNamesFromIds(IEnumerable<int> ids)
{
return ids.Select(i => "Rating" + i);
}
So, presuming a class like this:
public class Rating
{
public int Id { get; set; }
}
You could simply use:
// get the list of ratings from somewhere
var ratings = new List<Rating>();
// project each Rating object into an int by selecting the Id property
var ids = ratings.Select(r => r.Id);
// project each int value into a string using the method above
var names = GetNamesFromIds(ids);
Or generally, any IEnumerable<int> would work the same:
// get ids from a list of ratings
names = GetNamesFromIds(ratings.Select(r => r.Id));
// get ids from an array
names = GetNamesFromIds(new [] { 1, 2, 3, 4, 5});
// get ids from Enumerable.Range
names = GetNamesFromIds(Enumerable.Range(1, 5));