[英]How to update a list based on more than one Condition using LINQ C#
我有一个用竖线符号“ |
”分隔的字符串,我在分割字符串并转换为List<string>
。 如果List<string>
包含字符串“ Fax ”,则使用嵌入式Single LINQ语句将该字符串替换为“ A ”,与字符串“ phone ”相同,替换为字符串“ B”。 不要尝试替换基本字符串str
string str = "fax|mobile|phone";
str.Split('|').Where(i => i.ToLowerInvariant() == "fax" || i.ToLowerInvariant() == "phone").ToList();
因此,我的预期输出应为
List<string>() {"A", "B"}
使用select转换输出。
str.Split('|')
.Where(i => i.ToLowerInvariant() == "fax" || i.ToLowerInvariant() == "phone")
.Select(x=> x=="fax"? "A" : x=="phone"? "B" : x)
.ToList();
它是这样的:
string str = "fax|mobile|phone";
var result = str.Split('|').Select(i =>
string.Equals(i, "fax", StringComparison.InvariantCultureIgnoreCase) ? "A" :
string.Equals(i, "phone", StringComparison.InvariantCultureIgnoreCase) ? "B" :
null)
.Where(i => i != null)
.ToList();
请不要更改字符串的大小写以进行比较。 有进行区分大小写的比较的非常好的方法。
此代码非常容易变得不可读。 更好的解决方案是使用单独的Dictionary<,>
:
var dict = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
dict.Add("fax", "A");
dict.Add("phone", "B");
string str = "fax|mobile|phone";
var result = str.Split('|').Select(i => {
string r;
dict.TryGetValue(i, out r);
return r;
})
.Where(i => i != null)
.ToList();
尝试这个:
string str = "fax|mobile|phone";
var result = str.Split('|').Where(i => i.ToLowerInvariant() == "fax" || i.ToLowerInvariant() == "phone").Select(i =>
i.ToLowerInvariant() == "fax" ? "A" : "B").ToList();
我敢肯定有更好的解决方案,但这是我的看法:
string str = "fax|mobile|phone";
List<string> list = str.Split('|')
.Select(x => x.ToLowerInvariant() == "fax" ? "A" : x.ToLowerInvariant() == "phone" ? "B" : null)
.ToList();
list.Remove(null);
list.Remove(null);
可以用Where
子句代替以获取一个内衬:
List<string> list = str.Split('|')
.Select(x => x.ToLowerInvariant() == "fax" ? "A" : x.ToLowerInvariant() == "phone" ? "B" : null)
.Where(x => x != null)
.ToList();
一个好主意是有一个单独的方法来获取匹配的字符串:
public string GetMatch(string s)
{
// Easier to maintain
return s.ToLowerInvariant() == "fax" ? "A" : s.ToLowerInvariant() == "phone" ? "B" : null;
}
然后做:
List<string> list = str.Split('|')
.Select(x => GetMatch(x))
.Where(x => x != null)
.ToList();
基于xanatos解决方案
var string s = string.Empty;
var dic = new Dictionary<string,string>(StringComparer.InvariantCultureIgnoreCase)
{
{"fax","a"},{"phone","b"}
}
var result = (from w in str.split('|') where dic.TryGetValue(w, out s) select s).toList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.