C#使用对象数组初始化信息,对搜索条件进行模糊匹配,并且不区分大小写,对商品列表进行格式化,要求动态的使用字符串for循环
时间: 2023-12-31 16:04:31 浏览: 29
好的,我理解了你的问题。针对你的问题,我可以给你一些思路和代码实现的建议。
首先,使用对象数组初始化信息,可以定义一个类来表示商品信息,例如:
```csharp
class Product {
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
}
```
然后,可以定义一个对象数组来存储商品信息,例如:
```csharp
Product[] products = new Product[] {
new Product { Name = "Apple iPhone 12", Description = "The latest iPhone from Apple", Price = 999.99 },
new Product { Name = "Samsung Galaxy S21", Description = "The latest smartphone from Samsung", Price = 799.99 },
new Product { Name = "Google Pixel 5", Description = "The best camera phone from Google", Price = 699.99 }
};
```
接下来,对搜索条件进行模糊匹配,可以使用 LINQ 查询来筛选符合条件的商品信息,例如:
```csharp
string search = "iphone";
var filteredProducts = from p in products
where p.Name.ToLower().Contains(search.ToLower())
select p;
```
这里使用 `ToLower()` 方法将搜索条件和商品名称转换为小写字母,然后使用 `Contains()` 方法来判断是否包含搜索条件。
然后,对商品列表进行格式化,可以使用字符串的格式化功能,例如:
```csharp
foreach (var p in filteredProducts) {
Console.WriteLine("{0,-20} {1,-50} {2,10:C}", p.Name, p.Description, p.Price);
}
```
这里使用字符串的占位符来指定每列的宽度和对齐方式,其中 `-` 表示左对齐,`10` 表示列宽为 10 个字符,`C` 表示货币格式。
最后,要求动态的使用字符串 for 循环,可以使用 `for` 循环来动态生成字符串,例如:
```csharp
string result = "";
for (int i = 0; i < 10; i++) {
result += i.ToString() + " ";
}
Console.WriteLine(result);
```
这里使用 `+=` 操作符来逐步拼接字符串,生成类似于 `0 1 2 3 4 5 6 7 8 9 ` 的字符串。
希望这些代码能够对你有所帮助!