排列C#中匹配模式的数组值
本文关键字:数组 模式 排列 | 更新日期: 2023-09-27 18:27:26
任何人都能帮助我根据特定值更改数组顺序吗?即,如果我的array=[0,1,2,3,4,5,6],并且我想重新排列数组值。如果a的值为5,那么数组的顺序应该是[5,6,0,1,2,3.4],如果值为4,那么数组应该从[4,5,60,1,2,3]开始。
string[] GetDays; //"Here i will get value from User"
string value; //"This value will also come from User but will always be present in above Array"
if(GetDays.Find(value))
{
//Rearrange the sort starting with value in ascending
}
注意:数组元素不是恒定的,所以我们必须用程序排列顺序,因为某个时间数组可以是[1,3,5,6],如果我的值为5,那么我的数组应该像[5,6,1,3]一样变化。感谢
这只需几行即可实现:
int[] test = {0, 1, 2, 3, 4, 5, 6};
var userValue = 3;
var sorted = test.GroupBy(i => i < userValue).OrderBy(i => i.Key)
.Select(i => i.OrderBy(j => j)).SelectMany(i => i).ToArray();
输出:
{3,4,5,6,0,1,2}
string[] GetDays = {"s","t","a","c","k"};
string [] temparray = new string[GetDays.Length];
string value = "c";
int index = Array.IndexOf<string>(GetDays, value);
for(int i=0;i<GetDays.Length;i++)
{
temparray[i] = GetDays[inde];
index = index+1>=GetDays.Length?0:index+1;
}
并且temparray
将包含期望的输出。
使用数组。用比较器排序:如下所示:
var a=new []{1,2,3,4,5,6};
var v=5;
//Create IComparer
Comparison<int> comparison = (x,y) => (x >= v && y < v)
? -1 // Case x is over user value but y is not: x ordered before y
: x.CompareTo(y); // otherwise standard comparison;
Array.Sort(a, comparison);