简体   繁体   English

在C#中基于两个定界符分割字符串

[英]Split string based on two delimiter in C#

Question - I am having a file(info.ref) that contains information in a specific format (refrence id |email addresses) eg: 问题 -我有一个文件(info.ref),其中包含特定格式的信息(参考ID |电子邮件地址),例如:

ref1|a@a.com,b@b.com,c@c.com   
ref2|c@c.com,d@d.com

I also fetch refrence id from another file (say ref1).I need to iterate through this file and then want to send email to all email id`s assosiated with this refrence Id. 我还从另一个文件(例如ref1)中获取参考ID,我需要遍历此文件,然后希望将电子邮件发送到与此参考ID相关联的所有电子邮件ID。

What I tried- 我尝试过的

 using (var streamReader = new StreamReader("info.ref"))
                            {
                                string line1="";
                                while((line1 = streamReader.ReadLine()) != null)
                                {
                                    var parameters =
                                       from line11 in line1
                                       let split = line1.Split('|')
                                       select new { name = split.First(), value = split.Skip(1) };

                                   //email logic to be written


                                }

Problem -How to get email list from this "parameters". 问题 -如何从此“参数”获取电子邮件列表。

Note -I understand that I can split the string with "|" 注意 -我知道我可以用“ |”分割字符串 as delimiters and again split with "," as delimiter and store in array.But can someone please guide what is wrong with the code I have written and how to retreive email addresses?and which is better way?. 作为分隔符,然后再次用“,”分隔并存储在数组中。但是有人可以指导我编写的代码有什么问题以及如何获取电子邮件地址吗?哪种方法更好?

Thanks in advance. 提前致谢。

You haven't split the emails by comma yet and you don't need the LINQ query in the loop: 您尚未按逗号分隔电子邮件,并且循环中不需要LINQ查询:

string[] tokens = line1.Split('|');
if(tokens.Length >= 2)
{
    string name = tokens[0];
    string[] emails = tokens[1].Split(',');
}

If you are learning LINQ, you could use File.ReadLines and following query: 如果您正在学习LINQ,则可以使用File.ReadLines和以下查询:

var allInfos = from line in System.IO.File.ReadLines("info.ref")
               let tokens = line.Split('|')
               where tokens.Length >=  2
               select new { name = tokens[0], emails = tokens[1].Split(',') };

foreach(var info in allInfos)
    Console.WriteLine("Name:{0} Emails{1}", info.name, String.Join(",", info.emails));

You can also split by multiple separators (assuming that ref cannont contain , char)): 您还可以按多个分隔符进行拆分(假设ref cannont包含, char):

var emails = line1.Split('|', ',').Skip(1); //skipping ref

or: 要么:

var splitted = line1.Split('|', ',');
var paramerers = 
       new 
       {
           name = splitted.FirstOrDefault(), //for case of empty line
           value = spliited.Skip(1)
       };

//usage
var emails = parameters.value.ToArray(); // f.e.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM