![](/img/trans.png)
[英]C# How do I replace objects in one collection with Objects from another collection
[英]C# How can I do a string replace method on the collection?
我有以下方法返回一个集合,然后我可以在MVC中构建一个下拉菜单。 问题是,我想替换集合中的值中的子字符串,但我不知道如何在C#中这样做(我是一个经典的vb家伙)。
public class RolesManagement
{
public static IEnumerable<string> BuildRoles(string DesiredRole)
{
var UserRoles = Roles.GetAllRoles();
IEnumerable<string> roles;
roles = UserRoles.Where(x => x.Contains("Sub")).Except(rejectAdmin);
return roles;
}
}
为简洁起见,上述内容已经简化。 角色集合中的每个角色如下所示:SubUser SubAdmin SubManager。
我只想返回用户管理员
请问C#中最好的方法是什么?
我的猜测是我必须做一个foreach并替换每个循环上的子字符串并在移动到下一个项目之前重新填充该值。
如果你能提供一个很棒的代码示例,因为我似乎还在喋喋不休地解决语法问题。
非常感激!
你可以用LINQ做到这一点。
roles = UserRoles
.Where(x => x.Contains("Sub"))
.Except(rejectAdmin)
.Select(x => x.Replace("Sub", ""));
编辑:请注意,此方法只是替换roles
中所有字符串中出现的所有字符串“Sub”。 这是一个非常广泛的行程,如果你只想做你提到的替换,你可能需要使用不同的lambda函数。 请参阅Romoku的帖子以获取帮助。
我会说,如果角色不会经常改变,那么制作一个映射Dictionary
。
public class RolesManagement
{
private static readonly Dictionary<string,string> RoleMapping =
new Dictionary<string,string>
{
{"SubUser", "User" },
{"SubManager", "Manager" },
{"SubAdmin", "Admin" }
};
public static IEnumerable<string> BuildRoles(string DesiredRole)
{
var UserRoles = Roles.GetAllRoles();
IEnumerable<string> roles;
roles = UserRoles.Where(x => x.Contains("Sub")).Except(rejectAdmin);
return roles.Select(r => RoleMapping.ContainsKey(r) ? RoleMapping[r] : r);
}
}
或者只是将它们作为FriendlyName
列存储在数据库中。
这将返回所有以sub开头的项目,并删除子
IEnumerable<string> = UserRoles .Where(x => x.StartsWith("sub")) .Select(y => y.Remove(0,3));
public static IEnumerable<string> GetCorrectedRoleNames(IEnumerable<string> roles)
{
List<string> correctedRoles = new List<string>();
foreach (string role in roles)
correctedRoles.Add(Regex.Replace(role, "Sub", string.Empty));
return correctedRoles.AsEnumerable();
}
public static IEnumerable<string> BuildRoles(string DesiredRole)
{
var UserRoles = Roles.GetAllRoles();
IEnumerable<string> roles;
roles = UserRoles.Where(x => x.Contains("Sub")).Except(rejectAdmin).Select(x=>x.Replace("Sub","");
return roles;
}
我认为x是string
变量,如果不是你必须在字符串集合上执行此替换
如果我理解你的问题,你需要删除字符串中“Sub”的出现。 如果您有其他条件,可以执行其他检查,例如“Sub”位于字符串的开头,不区分大小写等。
其中一种方法是找到要删除的字符串的索引然后删除。
var s = "SubUser";
var t = s.Remove(s.IndexOf("Sub"), "Sub".Length);
或者,您也可以使用空字符串替换要删除的字符串。
var t = s.Replace("Sub", "");
希望有所帮助。
尝试这个
List<string> x = new List<string>();
x.Add("SubUser");
x.Add("SubAdmin");
x.Add("SubManager");
var m = x.Select( y => y.Replace("Sub", ""));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.