简体   繁体   English

在C#中对字符串和部分对象名称使用串联

[英]Using concatenation with strings and partial object names in C#

Im looking for a way to gain the name of an object through the ID that it has been set to. 我正在寻找一种通过设置对象的ID获得对象名称的方法。
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 . "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? 是否有任何方法可以将部分对象名称和变量连接起来以构造对象名称,还是仅仅是遍历数组的情况?

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 自然,您需要更改代码以适合您的需求,但是对于名为Test的类,它将把它打印到Debug输出窗口中

Test0
Test1
Test2
Test3
Test4

Generally, to project a collection of objects, you would use LINQ, or more specifically IEnumerable.Select . 通常,要投影对象的集合,可以使用LINQ,或更具体地说是IEnumerable.Select In this case, you are projecting an int (the Id property of type int ) into a string , so the general method is: 在这种情况下,您要将一个int (类型为intId属性)投影到一个string ,因此常规方法是:

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: 或通常,任何IEnumerable<int>都可以相同地工作:

// 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM