如何使用LINQ从ICollection到IDictionary中选择某些值

时间:2019-01-12 16:08:38

标签: c# linq

我有IDictionary<int,bool?>,其中int-id,bool?-状态(真,假,空) 因此,我需要过滤ICollection个对象,在这里我应该将内部ID与我的IDictionary的ID进行比较,如果ID相同且状态为true-我应该选择此元素(使用LINQ)< / p>

我尝试过:incomeCollection.Values.Select(x=>x.InternalId.Equals(dataFromDictionary.Keys.Any)).Select(h=> new Item){Item = h.Name}

,但不起作用。我需要使用LINQ检查所有满足上述条件的collection和select元素。我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:3)

该词典有一个方便的TryGetValue方法,可以快速查找条目。

class Income
{
    public int InternalId { get; set; }
    public string Name { get; set; }
}

var dictionary = new Dictionary<int,bool?>
{
    {1, false},
    {2, true},
    {3, null},
};

var incomeCollection = new List<Income>
{
    new Income { InternalId = 1, Name = "A" },
    new Income { InternalId = 2, Name = "B" },
    new Income { InternalId = 3, Name = "C" },
    new Income { InternalId = 4, Name = "D" },
};

var result = incomeCollection.Where(x =>
    dictionary.TryGetValue(x.InternalId, out var status) && status == true)
    .Select(h=> new {Item = h.Name});

这比您的第一个使用dataFromDictionary.Keys.Any的方法要好,后者没有利用快速查找的Dictionary功能。

答案 1 :(得分:0)

可以使用

ToDictionary方法,如下面的示例所示。

为了仅从ICollection中选择几个值,可以使用where子句。

List<Package> packages =
        new List<Package>
            { new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L },
              new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L },
              new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L },
              new Package { Company = "Adventure Works", Weight = 33.8, TrackingNumber = 4665518773L } };

    // Create a Dictionary of Package objects, 
    // using TrackingNumber as the key.
    Dictionary<long, Package> dictionary =
        packages.ToDictionary(p => p.TrackingNumber);

    foreach (KeyValuePair<long, Package> kvp in dictionary)
    {
        Console.WriteLine(
            "Key {0}: {1}, {2} pounds",
            kvp.Key,
            kvp.Value.Company,
            kvp.Value.Weight);
    }

答案 2 :(得分:0)

您可以使用Any()

var result = list.Where(x=>dictionary.Keys.Any(c=>c.Equals(x.Id))  && x.State.HasValue && x.State==true).Select(x=>x);

您还可以使用Join。

var result = list.Join(dictionary,
                        l=>l.Id, 
                        d=>d.Key,(l,d)=>l)
                  .Where(x=>x.State.HasValue && x.State==true).Select(x=>x);

例如,

var dictionary = new Dictionary<int,bool?>
{
        [1] = true,
        [3] = true,
        [35] = false
};
var list = new List<Person>
{
  new Person{Name="Jia", Id=1,State=false},
  new Person{Name="Aami", Id=3,State=true},
  new Person{Name="Anu", Id=35,State=null},
};

输出

Aami 3 True