[英]Dynamicly remove and add another letter from a List<> keeping alphabetical order
I have this predefined string array : 我有这个预定义的字符串数组:
string[] SkippedAreasArray = new string[] {"A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q"};
And according to an user input I populate a List<string>
like this : 根据用户输入,我像这样填充
List<string>
:
List<String> UsedAreas = new List<String>();
int RangeOfInput = (int)entity.AreasCnt;
UsedAreas = SkippedAreasArray.ToList().GetRange(0, RangeOfInput);
Also from an user input I get another string containing non-duplicated letters from A to Q
(like in SkippedAreasArray
). 同样从用户输入中,我得到另一个字符串,其中包含从
A to Q
非重复字母(例如SkippedAreasArray
)。
The array is formed like this : 数组是这样形成的:
SkippedAreasFromForm = (txtSkippedAreas.Text).ToUpper().Split(',');
What I do is first - sorting the SkippedAreasFromForm
: 我要做的是首先-对
SkippedAreasFromForm
排序:
Array.Sort<string>(SkippedAreasFromForm);
And then I need the following : 然后我需要以下内容:
foreach (string tempAreaValue in SkippedAreasFromForm)
{
if (UsedAreas.Contains(tempAreaValue))
{
}
else
{
}
}
if the List<> UsedAreas
contains the letter that is checked I want to remove this letter from the List and at the same time to add the next letter that follows in alphabetical order. 如果
List<> UsedAreas
包含已选中的字母,我想从列表中删除该字母,同时添加按字母顺序排列的下一个字母。
PS PS
I see now that my goal is not clear here so I'll explain the meaning of this : 现在我知道我的目标还不清楚,因此我将解释其含义:
SkippedAreasFromForm
is an user input that should be validated and that's the idea to want this algorithm. SkippedAreasFromForm
是应该验证的用户输入,这就是需要此算法的想法。 If in some case if (UsedAreas.Contains(tempAreaValue))
returns false then the input is wrong and I need to return error message. 如果在某些情况下
if (UsedAreas.Contains(tempAreaValue))
返回false,则输入错误,我需要返回错误消息。
You can use LINQ to Objects to achieve that without looping: 您可以使用LINQ to Objects来实现,而无需循环:
UsedAreas = SkippedAreasArray.Except(SkippedAreasFromForm)
.OrderBy(e => e)
.Take(RangeOfInput)
.ToList();
It's taking RangeOfInput
elements from SkippedAreasArray
that are not in SkippedAreasFromForm
. 它从
SkippedAreasArray
中获取RangeOfInput
元素,这些元素不在SkippedAreasFromForm
。 Result is List<string>
. 结果是
List<string>
。
Update 更新
You can check your error message condition that way: 您可以通过以下方式检查错误消息条件:
if(SkippedAreasFromForm.Except(SkippedAreasArray.Take(RangeOfInput)).Any())
{
// incorrect user input
}
IEnumerable<string> usedAreas = SkippedAreasArray.Take(RangeOfInput);
IEnumerable<string> skippedAreasFromForm = (txtSkippedAreas.Text).ToUpper()
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
IEnumerable<string> invalids = skippedAreasFromForm.Except(usedAreas);
if (invalids.Any())
MessageBox.Show(string.Format("These are invalid: [{0}]",
string.Join(",", invalids.OrderBy(sa => sa))));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.