string[] arr = { "abcdefXXX872358", "abcdef200X8XXX58", "abcdef200X872359", "6T1XXXXXXXXXXXX11", "7AbcdeHA30XXX541", "7AbcdeHA30XXX691" };
如何从上面获得前6个字符必须区分的不同数字 结果将是
abcdefXXX872358
6T1XXXXXXXXXXXX11
7AbcdeHA30XXX541
我尝试这样的事情
var dist = (from c in arr
select c).Select(a => a.Substring(0, 5)).Distinct();
这给了我前5个字符,但我想要整个字符串
答案 0 :(得分:6)
对第一个字符进行分组,并获取每个组中的第一个字符串:
IEnumerable<string> firstInGroup =
arr
.GroupBy(s => s.Substring(0, 6))
.Select(g => g.First());
答案 1 :(得分:0)
我认为最好的方法是实现IEqualityComparer,正如List.Distinct()上的重载所暗示的那样
public class firstXCharsComparer : IEqualityComparer<string>
{
private int numChars;
public firstXCharsComparer(int numChars)
{
this.numChars = numChars;
}
public bool Equals(string x, string y)
{
return x.Substring(0, numChars) == y.Substring(0, numChars);
}
public int GetHashCode(string obj)
{
return obj.Substring(0, numChars).GetHashCode();
}
}
static void Main(string[] args)
{
string[] arr = { "abcdefXXX872358", "abcdef200X8XXX58", "abcdef200X872359", "6T1XXXXXXXXXXXX11", "7AbcdeHA30XXX541", "7AbcdeHA30XXX691" };
var result = arr.ToList().Distinct(new firstXCharsComparer(6));
result.Count();
}