2

这是我的问题

我有以下数组(例如)

string[] arr = new[] { "s_0001", "s_0002", "s_0003", "sa_0004", "sa_0005", "sab_0006", "sab_0007" };

我想做一些给出以下输出的事情

s_0001
sa_0004
sab_0006

我已经尝试了一切,但没有运气!这将是一个长期项目的第一步,任何帮助将不胜感激。

[编辑] 我不知道字母什么时候会改变,但我知道总会有一个下划线来分隔字母和数字。我需要以某种方式提取这些字母,然后去掉重复的

[编辑]更具体地说..我想在下划线之前有每个字符串的唯一条目,我不关心的数字

[编辑] 好的,伙计们!你真的很活跃,我给你。我没想到我会得到这么快的答案。但看起来(因为我在过去 8 小时里一直在研究这个问题)我问错了问题

这是我的代码

//Loop through the XML files in the Directory and get
//the objectName and GUID of each file
string[] arr_xmlFiles = Directory.GetFiles(Dir, "*.xml");   //Array with all XML Files in the Directory

foreach (string xmlFile in arr_xmlFiles)
{
    try
    {
        //Get the XMLs Name
        XDocument xmlF = XDocument.Load(xmlFile);
        string objectName = xmlF.Root.Name.ToString();

        //Get the XMLs GUID
        XElement oDcElement = xmlF.Root.FirstNode as XElement;
        Guid oGuid = new Guid(oDcElement.Attribute("DataclassId").Value);

        //Prints out the results 
        Console.WriteLine(" " + objectName + "    " + oGuid);
    }
    catch (XmlException) { }
}

我所做的基本上是以下我在一个目录中获取所有 XML 文件(它们包含 ObjectName 及其 GUID)

IE

CM_Commands [0ee2ab91-4971-4fd3-9752-cf47c8ba4a01].xml    
CM_Commands [1f627f72-ca7b-4b07-8f93-c5750612c209].xml

抱歉,破坏符号是“[”而不是“_”,但这没关系。

现在我将所有这些 XML 保存在一个数组中,然后我想从这些 XML 中提取每个 XML 的 ObjectName 和 GUID

在我这样做之后,我只想对每个拥有相同 objectName 的 XML 之一进行一些修改

就这样

4

7 回答 7

3

编辑#3:添加到下面的代码片段的详细注释(请参阅EDIT 2下的更新代码)。另请注意,如果您想从方法中返回这些,则需要使用这些属性设置一个新类,例如:

public class MyClass 
{
    public string ObjectName { get; set; }
    public string Guid { get; set; }
    public string FileName { get; set; }
}

有了可用的类,select 语句将从select new { ... }变为:

/* start of query unchanged ... */
select new MyClass
{
    ObjectName = split[0],
    Guid = split[1],
    FileName = f.FullName
};

您的方法以及所有这些代码将具有返回类型IEnumerable<MyClass>. 您可以List<MyClass>通过使用轻松将其更改为return results.ToList();.

编辑#2:要从文件名中提取objectNameGuid,您不需要执行所有繁琐的 XML 工作来从内部详细信息中获取信息。

假设你的objectNameGuid总是用空格隔开,你可以使用下面的代码。否则可能需要更多的解析(或可选的正则表达式)。

string path = @"C:\Foo\Bar"; // your path goes here
var dirInfo = new DirectoryInfo(path);

// DirectoryInfo.GetFiles() returns an array of FileInfo[]
// FileInfo's Name property gives us the file's name without the full path
// LINQ let statement stores the split result, splitting the filename on spaces
// and dots to get the objectName, and Guid separated from the file extension.
// The "select new" projects the results into an anonymous type with the specified
// properties and respectively assigned values. I stored the fullpath just in case.
var query = from f in dirInfo.GetFiles("*.xml")
            let split = f.Name.Split(new[] { ' ', '.' })
            select new 
            {
                ObjectName = split[0],
                Guid = split[1],
                FileName = f.FullName
            };

// Now that the above query has neatly separated the ObjectName, we use LINQ
// to group by ObjectName (the group key). Multiple files may exist under the same
// key so we then select the First item from each group.
var results = query.GroupBy(o => o.ObjectName)
                   .Select(g => g.First());

// Iterate over the results using the projected property names.
foreach (var item in results)
{
    Console.WriteLine(item.FileName);
    Console.WriteLine("ObjectName: {0} -- Guid {1}", item.ObjectName, item.Guid);
}

这适合您的示例数据,但是如果您预期带有.字符的文件名,上述内容将会中断。要纠正这种情况变化:

  1. Split到:let split = f.Name.Split(' ')
  2. 指南:Guid = split[1].Substring(0, split[1].LastIndexOf('.')),


既然你知道总会有一个下划线,你可以试试这种方法:

string[] arr = {"s_0001", "s_0002", "s_0003", "sa_0004", "sa_0005", "sab_0006", "sab_0007"};

var query = arr.GroupBy(s => s.Substring(0, s.IndexOf('_')))
               .Select(g => g.First());

foreach (string s in query)
    Console.WriteLine(s);    // s_0001, sa_0004, sab_0006

这将采用每个组的第一项,因此除非您的项目是预先排序的,否则您可能需要OrderBySelect:.Select(g => g.OrderBy(s => s).First());

编辑:为了响应您的编辑,要获取下划线之前的不同字母(即s、sa、sab),您可以使用Enumerable.Distinct方法,如下所示:

var query = arr.Select(s => s.Substring(0, s.IndexOf('_')))
               .Distinct();    // s, sa, sab

如前所示,这将为您提供一个IEnumerable<string>可以迭代的 a foreach

于 2010-08-23T14:26:22.037 回答
2
Dictionary<string,string> lettersToRecords = new Dictionary<string,string>();
arr.Foreach((record) =>
    {
        string letters = record.Split('_')[0];
        if(!lettersToRecords.Keys.Contains(letters))
        {
            lettersToRecords[letters] = record;
        }
    });
于 2010-08-23T14:48:51.507 回答
1

这是我的第一直觉:

string[] arr = {"s_0001", "s_0002", "s_0003", "sa_0004", "sa_0005", "sab_0006", "sab_0007"};

arr.Select(a => Regex.Match(a,@"([A-Za-z]+)_([0-9]+)").Groups[1].ToString()).Distinct();
于 2010-08-23T14:38:27.403 回答
0

您可以string.Split('_')在数组中的每个字符串上使用。

记住前缀并在提取一个具有该前缀的单词后忽略所有具有相同前缀的单词。

如果数组有特定的顺序,你甚至可以优化一点。

于 2010-08-23T14:21:04.557 回答
0

arr[0] arr[3] arr[6]

于 2010-08-23T14:12:56.377 回答
0

所以本质上,数组的每个元素代表两个值:前缀(“s”、“sa”、“sab”)和后缀(“0001”、“0002”、“0003”、“0004”、“0005”、 “0006”、“0007”)。

这是一个使用 Linq 将字符串分解为前缀和后缀的示例,然后根据前缀将元素组合在一起。最后一步只是遍历分组并输出前缀以及使用该前缀找到的第一个元素的后缀:

string[] arr = new[] { "s_0001", "s_0002", "s_0003", "sa_0004", "sa_0005", "sab_0006", "sab_0007" };

var elementsByPrefix = arr.Select(s =>
{
    int indexOfUnderscore = s.IndexOf('_');
    if (indexOfUnderscore >= 0)
    {
        return new { Prefix = s.Substring(0, indexOfUnderscore), Suffix = s.Substring(indexOfUnderscore + 1, s.Length - (indexOfUnderscore + 1)) };
    }
    else
    {
        return new { Prefix = s, Suffix = string.Empty };
    }
}).GroupBy(item => item.Prefix);

foreach (var element in elementsByPrefix)
{
    Console.WriteLine("{0}_{1}", element.Key, element.First().Suffix);
}

此代码的输出与您的原始问题不完全匹配,因为这将输出“sab_0006”而不是“sab_0007”,但您并没有真正指定输出一个与另一个的规则是什么,所以我只是假设您想要具有该前缀的第一个元素或具有该前缀的任意元素。

于 2010-08-23T14:27:16.793 回答
0

据我所知,您想通过元素的前缀来区分集合,接下来执行以下操作:

class YourStringComparer : System.Collections.Generic.IEqualityComparer<string[]>
{
    public bool Equals(string[] x, string[] y)
    {
        throw new NotImplementedException(); // not used here
    }

    public int GetHashCode(string[] obj)
    {
        return obj.First().GetHashCode();
    }
}

string[] arr = new[] { "s_0001", "s_0002", "s_0003", "sa_0004", "sa_0005", "sab_0006", "sab_0007" };

var r = arr.Select(s => s.Split('_')).Distinct(new YourStringComparer());
// "s_0001", "sa_0004", "sab_0006"
于 2010-08-23T14:50:43.173 回答