这是我的场景!
List<String> list = new List<String>();
list.Add("E9215001");
list.Add("E9215045");
list.Add("E1115001");
list.Add("E1115022");
list.Add("E1115003");
list.Add("E2115041");
list.Add("E2115042");
list.Add("E4115021");
list.Add("E5115062");
我需要使用C#&amp;从上面列表中提取以下公共零件。linq
e92150 ->从{* e92150 *01,* e92150 *45} *45}
提取e11150 ->从{* e11150 *01,* e11150 *22,* e11150 e11150 *03}
e21150 ->从{* e21150 *41,* e21150 *42} e41150 ->从{* e41150 *21}
提取e51150 ->从{* e51150 *62}
提取更新:谢谢!每个人!借助@mlorbetske&amp;@shelleybutterfly我已经弄清楚了!
解决方案:
list.Select((item, index) => new {
Index=index,
Length=Enumerable.Range(1, (item.Length-2)) //I'm ignoring the last 2 characters
.Reverse()
.First(proposedLength => list.Count(innerItem =>
innerItem.StartsWith(item.Substring(0, proposedLength))) >
1)}).Select(n => list[n.Index].Substring(0, n.Length)).Distinct()
我怀疑这就是您要寻找的东西,但是
var result = list.Select(s => s.Substring(0, 6))
.Distinct();
我不确定确定匹配项的标准是什么,所以我已经写了这本书 - 完全新颖,是99.9999%的确定性,实际上不是您想要的。p>本质上,外部选择获得确定长度的所有子字符串。
第一个内部选择确定在列表中至少另一个字符串中找到的该字符串的最大长度。
组(按照第一个内部选择)组本身。
本身。然后将此分组转换为长度的字典与找到的次数。
然后,我们按频率( Value
)订购一组分组(升)。
接下来,我们将实际的长度(从Key
出现最少的长度),然后将其吐回Substring
的第二个参数,因此我们将子字符串从0到该长度。当然,我们现在又回到了外部选择,所以我们实际上得到了值(hooray!)。
现在,我们从该结果中获取独特的值集,瞧!
list.Select(
item => item.Substring(0,
list.Select(
innerItem => Enumerable.Range(1, innerItem.Length)
.Reverse()
.First(proposedlength => list.Count(innerInnerItem => innerInnerItem.StartsWith(innerItem.Substring(0, proposedlength))) > 1)
)
.GroupBy(length => length)
.ToDictionary(grouping => grouping.Key, grouping => grouping.Count())
.OrderBy(pair => pair.Value)
.Select(pair => pair.Key)
.First())
).Distinct()
阅读了上面的评论后,我看到在每个学期中找到其他任何一个中的最长最长的子字符串也有兴趣。这是更多新颖的代码:
list.Select((item, index) => new {
Index=index,
Length=Enumerable.Range(1, item.Length)
.Reverse()
.First(proposedLength => list.Count(innerItem => innerItem.StartsWith(item.Substring(0, proposedLength))) > 1)
}).Select(n => list[n.Index].Substring(0, n.Length))
.Distinct()
简而言之,从列表中的每个项目迭代,并从该元素的开头收集条目的索引和最长的子字符串,这些元素至少在列表中的另一个条目中可以找到。按照从每个索引/长度对收集所有子字符串并仅取独特的字符串。
是否需要是内联查询语法?如果是这样,那么:
var result =
from item in list
select item.Substring(0,6);
或明显的要求:
var result =
(
from item in list
select item.Substring(0,6);
)
.Distinct();
已解决!感谢 @ mlorbetske 和 @ Shelleybutterfly
list.Select((item, index) => new { Index=index,
Length=Enumerable.Range(1, (item.Length-2)) //I don't need the last 2 Char so I'm ignoring it
.Reverse()
.First(proposedLength => list.Count(innerItem =>
innerItem.StartsWith(item.Substring(0, proposedLength))) >
1)}).Select(n => list[n.Index].Substring(0, n.Length)).Distinct()