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?
Asked
Active
Viewed 2,400 times
0

Christoph Fink
- 22,727
- 9
- 68
- 113

matt
- 67
- 1
- 10
-
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. Oct 20 '14 at 11:43
-
You can use Linq but at the bottom line it will iterate through the members of the list/array anyway. – Amorphis Oct 20 '14 at 11:46
2 Answers
1
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

Joe
- 1,214
- 3
- 15
- 33
-
this seems to be the correct method but could it be implemented alongside `
.Text` or ` – matt Oct 20 '14 at 13:26.Value` @Joeb454 -
Do you mean when you have an instance of your class (e.g. a `Rating` object), or without an instance of the object available? – Joe Oct 20 '14 at 13:29
-
with an instance available/created, eg. lblCounter1.Text bu accessed through ("lblCounter" + i).Text? – matt Oct 20 '14 at 14:03
0
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));

vgru
- 49,838
- 16
- 120
- 201