将分隔字段转换为不同的排列记录Linq [英] Convert Delimited Fields Into Distinct Permutation Records Linq

查看:76
本文介绍了将分隔字段转换为不同的排列记录Linq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据表,其记录格式如下所示,其中PassA和PassB字段包含以逗号分隔的条目。



I have a data table that has records in a format like that shown below, where the PassA and PassB fields contain comma delimited entries.

PassA   PassB   OtherField
1,2,3   1,2     X
1,3     2       Y





您有什么建议来生成修改后的修改表,其中包括PassA和PassB中分隔条目的所有排列,如下所示:





What recommendations do you have for generating the modified modified table that includes all permutations of the delimited entries in PassA and PassB shown below:

PassA	PassB	OtherField
1	1	X
1	2	X
2	1	X
2	2	X
3	1	X
3	2	X
1	2	Y
3	2	Y





感谢您的考虑。



Thanks for your consideration.

推荐答案

它看起来很复杂,但它确实很简单。我将尝试在评论中解释:

It looks complex but it's simple really. I'll try to explain in comments:
// Test class represents your test data:
private static void Main()
{
   //UPDATE: Corrected test data type
   //Test data
   DataTable dt = new DataTable();

   dt.Columns.AddRange(new []
   {
       new DataColumn("PassA",typeof(string)),
       new DataColumn("PassB",typeof(string)),
       new DataColumn("Other",typeof(string)), 
   });

   DataRow row = dt.NewRow();
     row["PassA"] = "1,2,3";
     row["PassB"] = "1,2";
     row["Other"] = "X";
     dt.Rows.Add(row);
   row = dt.NewRow();
     row["PassA"] = "1,3";
     row["PassB"] = "2";
     row["Other"] = "Y";
     dt.Rows.Add(row);

   var fullList =
       dt.Rows.Cast<DataRow>().Select(i => new
       {
          //First select turns the string into an array
          PassA = i["PassA"].ToString().Split(','),
          PassB = i["PassB"].ToString().Split(','),
          Other = i["Other"].ToString()
       })
       //The object is now IEnumerable<anon><string[],string[],string>>
       //We need to merge the two string arrays
       .SelectMany(i =>  //We make the first array the subject, but we still want to return all results, so selectmany

            i.PassA.SelectMany(  //Same logic as before, but we'll use an overload
                  a => i.PassB,  //second subject
                 (a, b) => new {a, b, i.Other})); //select our new object type
       //By the end we have a IEnumerable<anon<string,string,string>>

  //Output for checking
  fullList.ToList().ForEach(i =&gt;
  {
    Console.WriteLine("{0}\t{1}\t{2}",i.a,i.b,i.Other);
  });
}





我希望这是有道理的。如果不是那么请告诉我^ _ ^

Andy



更新:将测试数据从POCO更改为DataTable:

主要逻辑是完整的。我仍然像以前一样将初始对象(现在是数据表)转换为anon



I hope that makes sense. if not then let me know ^_^
Andy

UPDATE: Changes test data from POCO to DataTable:
The main logic is intact. I still convert the initial object (now datatable) to anon as before


这篇关于将分隔字段转换为不同的排列记录Linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆