志在指尖
用双手敲打未来

C#中的自定义字符串排序方法

publicclassCustomStringComparer:System.Collections.Generic.IComparer<string>
{
#region
/*privateList<string>Convert(List<string>lists){
for(inti=0;i<lists.Count-1;i++)
{
for(intj=i+1;j<lists.Count;j++)
{
stringh1=lists;
stringh2=lists[j];
if(Compare1(h1,h2))//调用比较算法
{
stringtemp=lists[j];
[i]lists[j]=lists;
lists=temp;
}
}
}
returnlists;
}
privateboolCompare1(stringfileA,stringfileB)
{
if(string.IsNullOrEmpty(fileA)||string.IsNullOrEmpty(fileB))
thrownewArgumentException(“Parameterscan’tbenull”);
//stringfileA=xasstring;
//stringfileB=yasstring;
intresulta=0;
intresultb=0;
boolresult1=int.TryParse(fileA,outresulta);
boolresult2=int.TryParse(fileB,outresultb);
if(result1||result2)
{
if(result1&&result2)
{
returnresulta>resultb;
}
elseif(!result1)
{
returntrue;
}
elseif(!result2)
{
returnfalse;
}
returnfalse;
}
else
{
char[]arr1=fileA.ToCharArray();
char[]arr2=fileB.ToCharArray();
inti=0,j=0;
while(i<arr1.Length&&j<arr2.Length)
{
if(char.IsDigit(arr1)&&char.IsDigit(arr2[j]))
{
strings1=””,s2=””;
while(i<arr1.Length&&char.IsDigit(arr1))
{
s1+=arr1;
i++;
}
while(j<arr2.Length&&char.IsDigit(arr2[j]))
{
s2+=arr2[j];
j++;
}
if(int.Parse(s1)>int.Parse(s2))C#
{
returntrue;
}
elseif(int.Parse(s1)<int.Parse(s2))
{
returnfalse;
}
}
else
{
if(!char.IsDigit(arr1)&&!char.IsDigit(arr2[j]))
{
if(arr1>arr2[j])
{
returntrue;
}
elseif(arr1<arr2[j])
{
returnfalse;
}
}
elseif(char.IsDigit(arr1))
{
returnfalse;
}
elseif(char.IsDigit(arr2[j]))
{
returntrue;
}
i++;
j++;
}
}
if(arr1.Length>arr2.Length)
{
returntrue;
}
else
{
returnfalse;
}
}
}*/
#endregion
publicintCompare(stringfileA,stringfileB)
{
if(string.IsNullOrEmpty(fileA)||string.IsNullOrEmpty(fileB))
thrownewArgumentException(“Parameterscan’tbenull”);
intresulta=0;
intresultb=0;
boolresult1=int.TryParse(fileA,outresulta);
boolresult2=int.TryParse(fileB,outresultb);
if(result1||result2)//任意一个字符串为数值
{
//判断是否有为非数值
if(!result2)
{
return-1;
}
elseif(!result1)
{
return1;
}
else//都是数值
{
returnresulta>resultb?1:resulta<resultb?-1:0;
}
}
else//都包含非数值类型字符
{
char[]arr1=fileA.ToCharArray();
char[]arr2=fileB.ToCharArray();
inti=0,j=0;
while(i<arr1.Length&&j<arr2.Length)
{
if(char.IsDigit(arr1)&&char.IsDigit(arr2[j]))
{
strings1=””,s2=””;
while(i<arr1.Length&&char.IsDigit(arr1))
{
s1+=arr1;
i++;
}
while(j<arr2.Length&&char.IsDigit(arr2[j]))
{
s2+=arr2[j];
j++;
}
if(int.Parse(s1)>int.Parse(s2))
{
return1;
}
elseif(int.Parse(s1)<int.Parse(s2))
{
return-1;
}
}
else
{
if(!char.IsDigit(arr1)&&!char.IsDigit(arr2[j]))
{
if(arr1>arr2[j])
{
return1;
}
elseif(arr1<arr2[j])
{
return-1;
}
}
elseif(char.IsDigit(arr1))
{
return-1;
}
elseif(char.IsDigit(arr2[j]))
{
return1;
}
i++;
j++;
}
}
returnarr1.Length>arr2.Length?1:arr1.Length<arr2.Length?-1:0;
}
}
}

未经允许不得转载:IT技术网站 » C#中的自定义字符串排序方法
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载