C# 如何使用linq返回请求的形状?

C# 如何使用linq返回请求的形状?,c#,C#,如何在多行字符串中创建矩形并返回 是吗? 必须使用“*”字符生成该矩形。宽度是每行中的星星数,高度是行数 注意:您只能使用Enumerable和Linq生成 回答。不要在答案中使用“for”循环 示例:宽度=10,高度=5 结果: ********** ********** ********** ********** ********** 这应该可以做到: int width = 10, height = 5; IEnumerable<string> lines = Enumera

如何在多行字符串中创建矩形并返回 是吗?
必须使用“*”字符生成该矩形。宽度是每行中的星星数,高度是行数

注意:您只能使用Enumerable和Linq生成 回答。不要在答案中使用“for”循环

示例:宽度=10,高度=5

结果:

**********
**********
**********
**********
**********

这应该可以做到:

int width = 10, height = 5;
IEnumerable<string> lines = Enumerable.Repeat(new string('*', width), height);
String.Join()

另一编辑:

这将一步一步地解释代码。
我们首先来看这一行:

IEnumerable<string> lines = Enumerable.Repeat(new string('*', width), height);
IEnumerable lines=可枚举。重复(新字符串('*',宽度),高度);
IEnumerable
表示指定类型的数据的一种“集合”,用于存储矩形的各行

Enumerable.Repeat(TResult,Int32)
返回一个新的IEnumerable,其中填充了由
Int32
参数指定的一定数量的重复
TResult

带有参数
char
int
的字符串的构造函数创建了一个新的字符串实例,其中
char
参数重复的次数与
int
参数指定的次数相同

因此,本质上,你是:

  • 创建一个新的
    *
    字符字符串,重复
    宽度
  • 重复相同字符串的
    高度
    次,因为矩形的宽度不会跨行更改
  • 将结果存储在
    IEnumerable
    中以存储行(因为它们都来自
    IEnumerable
    ,数组和
    System.Collections.Generic.List
    也可以使用)
  • 然后将这些字符串连接在一个字符串中,各行之间用换行符(
    \n
    )分隔

  • 示例:宽度=10,高度=5结果:****************************************************************************************您尝试过什么?StackOverflow不是要求为家庭作业编写代码的地方
    Console.WriteLine(String.Join(“,Enumerable.Repeat(String.Join(“,Enumerable.Repeat(“*”,w))+“\n”,h))
    StackOverFlow.com!=HomeworkService.com
    虽然你的答案可能是正确的,但我反对投票,因为OP并没有表现出任何努力。是的,这是真的。。。我应该删除我的答案吗?我们可以看到答案的去向,也许帖子会被删除,尽管目前没有太多的版主。public static string GetStarBox(int-width,int-height){throw new NotImplementedException();}//该方法返回一个字符串值。感谢大家的回答,我认为将返回值修改为字符串是很容易的。虽然你的答案可能是正确的,但我反对投票,因为OP没有表现出任何努力。是的,这是真的。。。我应该删除我的答案吗?不要删除答案,伙计们,他们确实帮了我的忙。@Mardoxx我真的很喜欢你像Stefan那样复制粘贴了我的评论。@Mardoxx:请看这篇文章了解未来的案例:
    IEnumerable<string> lines = Enumerable.Repeat(new string('*', width), height);
    
    using System;
    using System.Linq;
    
    public class Test
    {
        public static void Main()
            {
                var w = 10;
                var h = 5;
                Console.WriteLine(String.Join("", Enumerable.Repeat(String.Join("", Enumerable.Repeat("*", w)) + "\n", h)));
            }
    }