如何创建列表< string>通过以更好的方式替换字符范围来从字符串中

发布于 2025-02-13 14:58:08 字数 362 浏览 0 评论 0原文

输入字符串:“ Hello_world_ {0}”

我需要创建一个类似于Hello_world_1,Hello_world_2,Hello_world_3等的字符串列表,等给定输入范围。

我已经尝试了以下方法,这很好。

string input = "Hello_World_{0}";
List<string> lst = new List<string>();
foreach (int value in Enumerable.Range(1, 10))
{
  lst.Add(string.Format(input,value));
}

我可以使用LINQ在一个衬里中实现相同的操作吗?

Input string: "Hello_World_{0}"

I need to create a string list which is like Hello_World_1,Hello_World_2,Hello_World_3,etc... to the given input range.

I have tried below approach, it's working fine.

string input = "Hello_World_{0}";
List<string> lst = new List<string>();
foreach (int value in Enumerable.Range(1, 10))
{
  lst.Add(string.Format(input,value));
}

Can I achieve the same in one liner using linq?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

策马西风 2025-02-20 14:58:08

选择 - &gt;从1 -10范围内获取每个项目。
输入字符串被每个项目替换,并创建字符串列表。
tolist-&gt;将此转换为列表。

string input = "Hello_World_{0}";
List<string> lst = Enumerable.Range(1, 10).Select(item => string.Format(input ,item)).ToList();

Select -> Fetches each item from the range of 1 -10.
Input string is replaced with each item and creates a list of strings.
ToList -> converts this into list.

string input = "Hello_World_{0}";
List<string> lst = Enumerable.Range(1, 10).Select(item => string.Format(input ,item)).ToList();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文