我有一个包含5个任意用户输入字符串的列表:
List<string> original = new List<string>() {"a", "a1", "a2", "b", "b1"} ;
对于原始集合中的每个字符串,我想返回列表中最短的字符串,该字符串将启动当前字符串:
"a" -> "a"
"a1" -> "a"
"a2" -> "a"
"b" -> "b"
"b1" -> "b"
如何使用LINQ执行此操作?
更多例子:
{a, ghjkjajj,hkj,bn,n} => {a, ghjkjajj,hkj,bn,n}
{ghj465,abn,abn1,hj,ui} => {ghj465,abn,abn,hj,ui}
{gh465,gh1,gh} => {gh,gh,gh}
{abcd,ab} => {ab,ab}
答案 0 :(得分:2)
由于一次不会超过5个字符串,因此效率不是问题。
var original = new List<string>() {"a","a1","c34","b","b1"};
var mapped = original.Select(x => original.Where(y => x.StartsWith(y)).Min()).ToList();
另请注意,比较区分大小写;这可以通过传递appropriate StringComparison argument来解决。
答案 1 :(得分:1)
此代码适用于我:
var res = original.Select(c => c.Replace(c.Length == 2 ? c[1] : ' ', ' ')).ToList();
输入:
{“a”,“a1”,“c34”,“a2”,“b”,“b1”}或{“a”,“a1”,“a2”,“b”,“b1”}
输出:
{“a”,“a”,“c34”,“a”,“b”,“b”}或{“a”,“a”,“a”,“b”,“b”}