[英]Using C#, From a list of strings, how do we find the one that most closely matches a test string?
[英]Check if list contains a string that matches closely
我正在嘗試找出實現以下情況的最有效方法:
我有一個這樣的清單:
public static IEnumerable<string> ValidTags = new List<string> {
"ABC.XYZ",
"PQR.SUB.UID",
"PQR.ALI.OBD",
};
我有一個包含多個列的大型CSV文件。 列之一是tags
。 此列包含空白值或以上值之一。 問題是,標簽列可能包含“ ABC.XYZ?@
”之類的值,即有效標簽加上一些多余的字符。 我需要使用有效標簽更新此類列,因為它們“ 緊密匹配 ”我們的有效標簽之一。
例:
PQR.ALI.OBD?
使用有效標簽PQR.ALI.OBD
更新它 PQR.ALI.OBA
,則此無效,只需添加后綴invalid並將其更新為PQR.ALI.OBA-invalid
。 我正在嘗試找出最佳方法。
我當前的方法是:
有沒有更好/更有效的方法來做到這一點?
更新:
該列表只有5個項目,這里顯示了三個項目。 多余的字符僅在末尾出現,這是因為人們正在用excel網絡版本編輯這些CSV,並且弄亂了某些條目。
我當前的代碼:(我確定有更好的方法可以做到這一點,這也是C#的新功能,所以請告訴我如何改進它)。 我正在使用CSVHelper來獲取CSV單元格。
var record = csv.GetRecord<Record>();
string tag = csv.GetField(10); //tag column number in CSV is 10
/* Criteria for validation:
* tag matches our list, but has extraneous chars - strip extraneous chars and update csv
* tag doesn't match our list - add suffix invalid.*/
int listIndex = 0;
bool valid;
foreach (var validTags in ValidTags) //ValidTags is the enum above
{
if (validTags.Contains(tag.ToUpper()) && !string.Equals(validTags, subjectIdentifier.ToUpper()))
{
valid = true;
continue; //move on to next csv row.
//this means that tag is valid but has some extra characters appended to it because of web excel, strip extra charts
}
listIndex++;
if(listIndex == 3 && !valid) {
//means we have reached the end of the list but not found valid tag
//add suffix invalid and move on to next csv row
}
}
由於您說附加字符僅在末尾,並且假定原始標簽仍在附加字符之前,因此您可以在列表中搜索每個標簽,以查看該標簽是否包含列表中的條目。 如果匹配,則將其更新為正確的條目(如果不完全匹配),如果不完全匹配,則將“ -invalid”標簽附加到該條目。
在執行此操作之前,我們可能需要首先對列表Descending進行排序,以便在搜索時找到最接近(最長)的匹配項(如果列表中的一項以列表中的另一項開頭)。
var csvPath = @"f:\public\temp\temp.csv";
var entriesUpdated = 0;
// Order the list so we match on the most similar match (ABC.DEF before ABC)
var orderedTags = ValidTags.OrderByDescending(t => t);
var newFileLines = new List<string>();
// Read each line in the file
foreach (var csvLine in File.ReadLines(csvPath))
{
// Get the columns
var columns = csvLine.Split(',');
// Process each column
for (int index = 0; index < columns.Length; index++)
{
var column = columns[index];
switch (index)
{
case 0: // tag column
var correctTag = orderedTags.FirstOrDefault(tag =>
column.IndexOf(tag, StringComparison.OrdinalIgnoreCase) > -1);
if (correctTag != null)
{
// This item contains a correct tag, so
// update it if it's not an exact match
if (column != correctTag)
{
columns[index] = correctTag;
entriesUpdated++;
}
}
else
{
// This column does not contain a correct tag, so mark it as invalid
columns[index] += "-invalid";
entriesUpdated++;
}
break;
// Other cases for other columns follow if needed
}
}
newFileLines.Add(string.Join(",", columns));
}
// Write the new lines if any were changed
if (entriesUpdated > 0) File.WriteAllLines(csvPath, newFileLines);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.