简体   繁体   English

根据另一个列表过滤通用列表

[英]Filter a generic list based on another list

I have a generic list which needs to be filter based on another list (say, List<string> ). 我有一个通用列表,需要根据另一个列表(例如List<string> )进行过滤。

public class Model
{
  public string ID { get; set;}
  public string Make { get; set;}
}

List<Model> lstModel = new List<Model>();

And the lstModel is as follows 而lstModel如下

 ID      Make
----    -----------
 5       MARUTI
 4       BENZ
 3       HYUNDAI
 2       HONDA
 1       TOYOTA

And i have another list which contains only car makers,ie 我还有另一个仅包含汽车制造商的列表,即

List<string> lstMakers = new List<string>() {"MARUTI", "HONDA"};

1) I need to filter lstModel which contains only items in lstMakers. 1)我需要过滤仅包含lstMakers中项目的lstModel。 The output would be 输出将是

 ID      Make
----    -----------
 5       MARUTI
 2       HONDA

2) Based on output (1), need another list of ids with 1 increment to each item in descending order, The output would be List<int> ie, 2)基于输出(1),需要另一个id列表,每个id都以降序递增1,输出将为List<int>即,

  6
  5
  3
  2

Note: Using lambda expression / linq is more preferable 注意:更优选使用lambda表达式/ linq

1 ) 1)

var list1 = lst.Where(x=>lstMakers.Contains(x.Make)).ToList();

2) 2)

var list2 = list1.Select(x=>int.Parse(x.ID)+1)
                 .Concat(list1.Select(x=>int.Parse(x))
                 .OrderByDescending(x=>x)
                 .ToList();

Use Enumerable.Join and OrderByDescending : 使用Enumerable.JoinOrderByDescending

var models = from maker in lstMakers
             join model in lstModel
             on maker equals model.Make
             select model;
List<int> result = models
    .Select(m => int.Parse(m.ID) + 1)
    .OrderByDescending(i => i)
    .ToList();

However, this selects two ints since only two models match. 但是,由于只有两个模型匹配,因此会选择两个ints Your result contains 4 ints . 您的结果包含4个ints I assume that your result is not related to your sample, is it? 我认为您的结果与您的样本无关,是吗?

but i need both the item and its incremental value,... 但是我需要项目及其增量值,...

Now it's clear, use Enumerable.SelectMany with an array: 现在很明显,将Enumerable.SelectMany与数组一起使用:

List<int> result = models
    .Select(m => int.Parse(m.ID))
    .SelectMany(id => new int[]{ id, id + 1 })
    .OrderByDescending(id => id)
    .Distinct()
    .ToList();

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

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