0

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?

2
  • 3
    You need to provide context/an example as I don't think its clear what you have and what you want to get. Commented 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. Commented Oct 20, 2014 at 11:46

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

this seems to be the correct method but could it be implemented alongside <objectname>.Text or <objectname>.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?
with an instance available/created, eg. lblCounter1.Text bu accessed through ("lblCounter" + i).Text?
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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.