【问题标题】:How to find distinct values from a specific index of a generic list如何从通用列表的特定索引中找到不同的值
【发布时间】:2019-04-17 09:59:51
【问题描述】:

我有一个通用列表

LinkedList<RelationModel> mylist = new LinkedList<RelationModel>();

此列表在两个索引 {0} 和 {1} 处获取输出。两个索引都有多个值。调试时,在

{0} - the output is     

Foreign             "Store"       --string
ForeignKeyColumn    "addressId"   --string
Primary             "Address"     --string
PrimaryKeyColumn    "addressId"   --string

{1} - the output is 

Foreign             "Address"     --string
ForeignKeyColumn    "countryId"   --string
Primary             "Country"     --string
PrimaryKeyColumn    "countryId"   --string

问题是我必须从列表中选择不同的值。例如——在这里,商店、地址和国家是不同的。如何在 C# 代码中选取这些值?

以下代码将数据填充到 mylist 中

using (var ctx = new TestDBEntities())
            {
                var foreginKeyList = ctx.Database
                .SqlQuery<MetdataModel>(" Select  [PKTABLE_NAME], [PKCOLUMN_NAME],[FKTABLE_NAME],[FKCOLUMN_NAME] from GetMetadata")
                .ToList();
                LinkedList<RelationModel> mylist = new LinkedList<RelationModel>();
                for (int i =0; i < foreginKeyList.Count; i++)
                {

                    var ss = foreginKeyList.Where(p => p.FKTABLE_NAME.Equals(foreginKeyList[i].FKTABLE_NAME)).Select(p => new { p.PKTABLE_NAME, p.PKCOLUMN_NAME }).ToList();
                    foreach(var col in ss)
                    {
                        RelationModel gg = new RelationModel();
                        gg.Foreign = foreginKeyList[i].FKTABLE_NAME;
                        gg.ForeignKeyColumn = foreginKeyList[i].FKCOLUMN_NAME;
                        gg.Primary = col.PKTABLE_NAME;
                        gg.PrimaryKeyColumn = col.PKCOLUMN_NAME;
                        mylist.AddLast(gg);

                    }

                }

我需要一个具有不同值的最终列表,例如

mylist.[0]- store
mylist.[1]- address
mylist.[2]- country

【问题讨论】:

  • 您希望Distinct在哪个属性上工作? PrimaryForeign ?因为您的结果列表两者都有?
  • Primay 和 Foreign 都是表名。我想获取不同的表名。如您所见,地址在 {1} 处重复。所以,我想从该输出中获取这些动态的不同值并将它们放在一个通用列表中。例如,如果地址放在 {0} 的列表中,则在通过 {1} 索引时不应将其添加到列表中
  • "此列表在两个索引 {0} 和 {1} 处获取输出。" - 你能改写这个/解释得更清楚吗?我认为你不关心 KeyColumn 值?
  • 不。我只想获取表名。它们在“Primary”和“Foreign”中获取

标签: c# linq collections generic-list


【解决方案1】:

假设RelationModel

public class RelationModel {
    public string Foriegn;
    public string ForeignKeyColumn;
    public string Primary;
    public string PrimaryKeyColumn;
}

那么您可以使用以下内容:

var ans = mylist.SelectMany(m => new[] { m.Foriegn, m.Primary }).Distinct().ToList();

现在您可以通过ans[0]ans[1] 等方式访问ans 的元素。

【讨论】:

  • 当我使用 ans.ToList();它说“无法使用 [] 将索引应用于 'IEnumerable' 类型的表达式”所以,当我写 'ans.[0]' 时,它给出了一个错误。如何解决这个问题?
  • @RahulDev 如果你在.Distinct() 之后添加.ToList() 你应该不会有这个问题。
猜你喜欢
  • 2021-11-19
  • 2020-03-22
  • 2023-01-21
  • 2020-10-12
  • 2021-11-17
  • 2011-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多