在 C# 中使用 Linq 更新现有列表
Updating an existing List using Linq in C#
我有如下列表和数据
public class Test
{
public int Id {get;set;}
public string Name {get;set;}
public string Quality {get;set;}
}
Test test = new Test();
//db call to get test data
//test = [{1,'ABC','Good'},{2,'GEF','Bad'}]
我必须修改列表,使 Name
应该只是前 2 个字符,Quality
应该是第一个字母。
预期输出:
//test = [{1,'A','G'},{2,'GE','B'}]
我尝试使用 Linq foreach
实现如下。但是我不确定在 Linq 中的 forloop 中编写条件语句导致错误。
test.ForEach(x=> return x.Take(1))
List.ForEach
虽然不是 LINQ
test.ForEach(t => { t.Name = t.Name.Length > 2 ? t.Name.Remove(2) : t.Name; t.Quality = t.Quality.Length > 1 ? t.Quality.Remove(1) : t.Quality; });
更好的方法是简单地调用执行此操作的方法。
test.ForEach(Modify);
private static void Modify(Test t)
{
// ,,,
}
您可以简单地使用 String.Substring 如下:
test.ForEach(s =>
{
s.Name = s.Name.Substring(0, 2);
s.Quality = s.Quality.Substring(0, 1);
});
谢谢,@Tim 指出如果 Name
或 Quality
很短,那么这段代码会抛出异常。请参阅 Problem with Substring() - ArgumentOutOfRangeException 了解可能的解决方案。
我有如下列表和数据
public class Test
{
public int Id {get;set;}
public string Name {get;set;}
public string Quality {get;set;}
}
Test test = new Test();
//db call to get test data
//test = [{1,'ABC','Good'},{2,'GEF','Bad'}]
我必须修改列表,使 Name
应该只是前 2 个字符,Quality
应该是第一个字母。
预期输出:
//test = [{1,'A','G'},{2,'GE','B'}]
我尝试使用 Linq foreach
实现如下。但是我不确定在 Linq 中的 forloop 中编写条件语句导致错误。
test.ForEach(x=> return x.Take(1))
List.ForEach
虽然不是 LINQ
test.ForEach(t => { t.Name = t.Name.Length > 2 ? t.Name.Remove(2) : t.Name; t.Quality = t.Quality.Length > 1 ? t.Quality.Remove(1) : t.Quality; });
更好的方法是简单地调用执行此操作的方法。
test.ForEach(Modify);
private static void Modify(Test t)
{
// ,,,
}
您可以简单地使用 String.Substring 如下:
test.ForEach(s =>
{
s.Name = s.Name.Substring(0, 2);
s.Quality = s.Quality.Substring(0, 1);
});
谢谢,@Tim 指出如果 Name
或 Quality
很短,那么这段代码会抛出异常。请参阅 Problem with Substring() - ArgumentOutOfRangeException 了解可能的解决方案。