LINQ在列表中找到所有id的id

时间:2017-04-23 10:40:59

标签: c# linq

我试图找出非查询方式,如果他们的ID在测试列表中,则返回所有对象的列表。示例如下:

Hero - table
Columns: id = INT , name = STRING, age = INT, power = INT;

var testList = {1,2,3};
var secondArray = {};

foreach (var id in testList )
{
    // check if ID in database
    var item = db.Hero.ToList().Find(o => o.Id = id);
    if( item != null)
    {
       secondArray.push(item);
    }
}

现在我已经看到这一切都是单线完成的,但不记得它是如何完成的。

我所追求的结果是包含id 1,2,3。

的所有对象的List

2 个答案:

答案 0 :(得分:2)

怎么样

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {

    private static class InputPair {
        public int radius;
        public int height;

        public InputPair() {}

        public void printValues() {
            System.out.println("Radius: " + radius + " Height: " + height);
        }
    }

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        System.out.print("Enter values ");
        String input = keyboard.nextLine();

        String[] items = input.split(" ");
        Integer[] integers = processItems(items);
        InputPair[] values = new InputPair[integers.length];

        System.out.println(Arrays.toString(items));
        System.out.println("items length:  " + items.length);

        System.out.println(Arrays.toString(integers));
        System.out.println("items length:  " + integers.length);

        if (integers.length % 2 == 0) { 
            for (int i = 0; i < integers.length / 2; i++) {
                System.out.print("Index:  " + i + " ");
                try {
                    values[i] = new InputPair();
                    values[i].radius = integers[i * 2];
                    values[i].height = integers[i * 2 + 1];
                    values[i].printValues();
                } catch (NullPointerException ne) {
                    System.out.println("Error NullPointerException");
                }

            }
        } else {
            System.out.println("The number of values bust be an even number. ");
        }
    }

    private static Integer[] processItems(String[] items) {
        List<Integer> numbers = new ArrayList<>();

        for (String s : items) {
            //Do your stuff here
            s = s.replaceAll("[^\\d]", "");
            if (!s.equals("")) {
                numbers.add(Integer.parseInt(s));
                System.out.println(Integer.parseInt(s));
            }
        }

        Integer[] stockArr = new Integer[numbers.size()];
        return numbers.toArray(stockArr);
    }
}

这只会击中DB一次而不是3次。

答案 1 :(得分:1)

您必须在Contains上使用testList

var secondArray= db.Hero.Where (h=> testList.Contains(h.Id))